PHP - Variable Scope
In this code...
class Model { public function getBook($title) { $allBooks = $this->getBookList(); return $allBooks[$title]; } } Questions: --------------- 1.) What is the scope of $allBooks? Can it be seen outside the function and inside the class? 2.) Could I rewrite things like this... Quote class Model { protected $allBooks; public function getBook($title) { $allBooks = $this->getBookList(); $this->allBooks = $this->getBookList(); return $allBooks[$title]; } } 3.) Sorta off-topic, but could I rewrite this code... Quote $allBooks = $this->getBookList(); return $allBooks[$title]; like this... Quote return $allBooks = $this->getBookList([$title]); TomTees Similar Tutorialsis there a way of having set variables for a specific include?...maybe be easier for me to explain via code
<?php $bee = 'yes'; include_one "a.php"; include_one "b.php"; // only b.php can grab $bee var ?>im wondering if I can only pass a var to b.php without a.php being able to use the var also? thanks guys I have an HTML form with a Dropdown list off dates. The Dropdown is populated using PHP and an array... Code: [Select] <?php $concertDates = array('201105071'=>'May 7, 2011 (9:00am - 12:00pm)', '201105072'=>'May 7, 2011 (1:00pm - 4:00pm)', '201105141'=>'May 14, 2011 (9:00am - 12:00pm)'); ?> When my HTML form is re-submitted to itself, what happens to $concertDates?? I was under the impression that it remains alive as long as my script is running... Debbie i have a text box, the no of text boxes that are displayed are random depending upon the condition of the loop.. hosting[] takes up many no of values <input type='text' name='hosting[]' size='2' /> when the form is submitted i use the following code to access the content of hosting[] $link_no = $_POST['hosting']; $total_actual_links = null; foreach($link_no as $total_link) { $total_actual_links[] = $total_link; } now i get the results in $total_actual_links[].. i want to pass the value of this array into the value of another text box of other form which i get on submission of the 1st form.. i do not knw how shud i do this.. please help I'm having a complete brainfart right now and can't seem to remember this. Tried looking it up in the manual, but couldn't find an example. Here's what I have: class myclass { function testA { } function testB { } } So that's my basic setup. I want to define a variable. I then want to set it's value in testA(). I then want to be able to access the value in testB(). Where and how do I define this variable? I thought all I had to do was something like: class myclass { public $tempvar=''; function testA { $tempvar="my new value"; } function testB { echo $tempvar; } } But this says that $tempvar is equal to NULL. What am I forgetting? Thanks in advance! Hi, im having a problem using a global object in all my scripts and programs. Its a register singleton so it have all the configuration values, etc... Now im doing: 1-I create a script for testing, test.php 2-I include in that script 'errores.php', thats my error system library. 3-The error library include once 'registroglobal.php', thats my file for the global register. 4-Because i can use a lot of systems with a complete library or alone, i created a system where i test if the library module is part of a more greater library or not. If not, it instantiates the global register in errors.php (called in the include in test.php). 5-Here is the problem. Includes add and execute code, so, i must have all errors.php functions and the global register created. 6-If i test the global register in the test.php script, it goes well. 7-But if i call a function of my errores.php system, it says that my global register is undefined. Well, thats all the explanation. Whats going on? How can i solve this? I am using a MVC framework and in my controller I have defined a class variable for configurations. In my action I have a call to the configuration class to set the class variable to the current configurations. Code: [Select] public $configArray = array(); public function actionBuild($id) { $this->configArray=Config::model()->getConfigArray($id); $this->buildStep1(); ... } When I echo the configuration in the method it is 10 but when I echo in buildStep1 it is 11. What is the proper way for configArray to be global and updated when I call getConfigArray for use in functions in the class? I'm having a problem with (what I'm almost certain is) variable scope, maybe you can help... So I've got a parent class that, among other things, gets the name of the filepath, explodes this filepath, checks for files with names that mirror that filepath (without the slashes of course), and includes them if they exist: class ParentClass { public $RootFolder; public $PageSections; function __construct() { global $root_folder; $this->RootFolder = $root_folder; //get all directory names... $cleanse = $this->RootFolder; $pagepath = str_replace($cleanse, '', dirname($_SERVER['PHP_SELF'])); $this->PageSections = explode('/', $pagepath); } function RequireIfExists ($sections, $root_folder, $file_name, $file_type) { foreach ($sections as $i){ if (isset($o)) { $i = $o."/".$i; } $file = $root_folder.$i."/".$file_name.$file_type; if (file_exists($_SERVER['DOCUMENT_ROOT'].$file)) { require ($_SERVER['DOCUMENT_ROOT'].$file); echo "<!--".$file." included -->"; //temporary measure to ensure that the file is at least being called. } $o = $i; } } // so, excuting the function // $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); // on some/sub/folder/index.php // will look for somesectionvars.php, somesubsecitonvars.php & somesubfoldersectionvars.php // and include whichever ones exist. } Then there is a child class that utilizes this function, and successfully requires the file. I know the file is coming through because the echo statement on the page shows up in the code, but I cannot get the variables to pass through? <?php class HtmlHead extends PageBlock{ public $PageKeywords; public $PageDescription; public $PageStyles; public $PageScripts; //------------------------ public $SectionKeywords; public $SectionDescription; //------------------------ public $SiteKeywords; public $SiteDescription; public $SiteStyles; public $SiteScripts; //------------------------ public $CatchAll; function __construct() { parent::__construct(); //$this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //I have tried calling the function here with no luck global $site_description, $site_keywords, $section_description, $section_keywords, $xyz; //also made sure to global the variables from the required page $this->SiteDescription = $site_description; $this->SiteKeywords = $site_keywords; $this->SectionDescription = $section_description; $this->SectionKeywords = $section_keywords; $this->PageDescription = $page_description; $this->PageKeywords = $page_keywords; } function Constructor() { $this->RequireIfExists($this->PageSections, $this->RootFolder, "sectionvars", ".php"); //Tried calling the function here as well, no luck global $xyz; //global'd the var i want echo "\n<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />"; echo "\n<!--Sec Keywords are".$xyz."-->"; //Tried to echo the var... //------------------------Rest of code... } } And here is the page that is being required... <?php echo "<!-- 1234 1234 1234 1234 -->"; //test measure to see if/where file is including $section_keywords = "red, secondary"; $section_description = "this is the red section description"; $xyz = "1234"; //test Var to see if there was a naming conflict with the above two.. ?> What am I overlooking this time? This is more of a technical question that i could not find the answer to pn the php.net manual pages. take the folowing example code: foreach ($array as $key => $value){ $tempvariable = some_property_of($value); } unset($tempvariable); is that unset statement needed? Does PHP automatically destroy the variables once the foreach loop is left? Hi Guys
I have a question about maintaining scope in OOP. I may just be going about it in completely the wrong way but I'm here to learn.
Lets say I have a base class called 'first; set out as per the code below.
In the first class there is a method that instantiates another class - called second. This second class extends the first class and I want it to be able to set errors on the first class. The only way I can maintain it's scope is to pass $this into the constructor of the second class.
My questions a
1) Is this the right way to maintain scope?
2) Would this be bad practice and I should explore a different model for setting out these classes?
3) Would it be considered better practice to make $errors a static property?
Keen to do things the right way so any advice is very welcome
class first { public $errors = array(); public function __construct(){ $this->callSecondClass(); $this->render(); } public function callSecondClass(){ $t = new second($this); } public function render(){ echo "I am rendering errors:"; print_r($this->errors); } } class second extends first { public function __construct($obj){ $obj->errors[] = 'ERROR FROM SECOND CLASS'; } } Edited by Drongo_III, 14 August 2014 - 04:54 PM. First: i'm pretty new to PHP. Second, the situation: i've got a array of universities. Each university within the array, which is also an array has values like an ID and Name. I wan't to add a value to that university from a xml feed, a URL. I can match ID's to find the corresponding university in the xml feed. Third, my question: Why do i lose the ['hURL'] outside of my foreach loop(s) ? It's working inside the foreach loop ... Fourth, here's the code: Code: [Select] $hDirectory = get_xml_feed('http://myawesomefeed.xml'); $universiteiten = array( $uniUtrecht = array('uniNaam' =>'Universiteit Utrecht', 'uniID' => 'uu'), $uniWageningen = array('uniNaam' =>'Wageningen University', 'uniID' => 'wur') ); foreach( $universiteiten as $universiteit ) { echo '<strong>' . $universiteit['uniNaam'] . ':' . '</strong> <br />'; foreach( $hDirectory->Entity as $school ) { if ( $universiteit['uniID'] == $school->orgUnitId ) { $hURL = (string) $school->DirectoryURL; $universiteit['uniURL'] = $hURL; echo 'Universiteit ID: ' . $universiteit['uniID'] . '<br />'; echo 'Hodex URL: ' . $universiteit['hURL'] . '<br /><br />'; //this works just fine } } } echo '<br/>'; print_r_html($uniUtrecht); // but here the [hURL] is missing I know this is a simple question, but it's been bugging the hell out of me. i am being told that i have an undefined variable - errorString - in a function, even though it *clearly* is defined w/i the scope of the function. Can somebody please help me out? Code: [Select] [Undefined variable: errorString/code] [php] /** * is fed a string email address and processes it to make sure that we're within limits: * * 1) must not be empty * 2) must not be above 50 characters * 3) must be in name@example.tld format * * returns TRUE if email is valid, string (with reasons for failure) if the email is not valid * * @param string $email * @return boolean|string */ public static function data_validateEmail($email){ // set up temporary vaiable $errorString; // check to see if the user's email is a null string if (empty($email)){ $errorString .="You must supply an email address. "; } // then check to see if its under 50 characters if(strlen($email) > 50){ $errorString .= "The email address can be no longer than 50 characters. "; } // then make sure it's in teh correct format if (!preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $email)) { $errorString .= "The email address must be in the name@domain.tld format. "; } // if we've got a valid email, return true... else, we return a string error if(empty($errorString)){ return true; } else { return $errorString; } } [/php] errorString is defined at the beginning of the function, so why am i told that it is undefined when, say, the length test fails? I know this has to be a simple solution, but ive spent almost 2 hours looking at it trying to figure it out, and have gotten nowhere.... :( and yes, part of that 2 hours was searching google for information about how PHP does variable scope in functions with multiple if statements... and all i could find was that as long as the variable is defined in the function scope, it should be available within the successive if statements. Thanks for reading! I need a bit of help understanding the scope of variables If I have the following code: Code: [Select] <?php $myvar = true; include(otherfile.php); ?> Is $myvar available for access as is in the code from otherfile.php? Specifically though, I'm trying to get my head round some Wordpress coding, so I have this instead: Code: [Select] <?php $myvar = true; <?php get_header(); ?> ?> <?php get_header(); ?> puts the contents of header.php at this location + I'm sure it does some other things like error checking etc What is the best way to have $myvar available? The ONLY thing is I only want $myvar = true just for one file - everywhere else it should be false or not exist I'm wary of using a global variable - but if it's the only way, then I have to Thanks Omar <?php function getglobal() { global $my_global; echo "The value of \$foobar is '$foobar' <br />"; } $my_global = 20; getglobal(); ?> It's supposed to give the result, Quote 'The value of $my_global is '20'; But instead when I try it, its giving me Quote Notice: Undefined variable: foobar in C:\wamper\www\php\index.php on line 17 The value of $foobar is '' So I don't really understand what's happening and why it's not working. I just started my journey into OOP, just looking for a simple explanation as to why the script echo's nothing. (last line) Code: (php) [Select] <?php class Dog { public $name; public function bark() { echo "{$this->name} says Woof!"; } } class Poodle extends Dog { public function bark() { echo "Yip"; } } $furball = new Poodle; $furball->name = "furball"; $furball->Dog::bark(); ?> In PHP? Let's say I'm going off of: width x height So this is 2x1 2x1 2 blocks across, 1 block height. How do I check this against other blocks in php to see if the 2x1 will overlap another set of dimensions dynamically? Am I over thinking this? Edited by Monkuar, 24 January 2015 - 12:08 PM. Hi. I'm sure this is a really simple problem!..but my inexperience is really showing me up! The problem is with defining the file that the function should read into $lines array. $lines = file('http://www.nickalm.com/rebuild/scripts/oil.txt'); With a string as the definition it works fine but with a variable (which I need) - no joy! Here's some code that works just fine... <?php function get_value_of($name){ $lines = file('http://www.nickalm.com/rebuild/scripts/oil.txt'); // this is the troublesome little devil here foreach (array_values($lines) as $line) { list($key, $val) = explode('=', trim($line) ); if (trim($key) == $name) { return $val; iconv( "UTF-8", "ISO-1252//TRANSLIT", $val ); } } return false; } ?> ...however...this just doesn't: $title_path = 'http://www.nickalm.com/rebuild/scripts/'.$gallery.'.txt'; function get_value_of($name) { $lines = file($GLOBALS['$title_path']); // this is the troublesome little devil here foreach (array_values($lines) as $line) { list($key, $val) = explode('=', trim($line) ); if (trim($key) == $name) { return $val; iconv( "UTF-8", "ISO-1252//TRANSLIT", $val ); } } return false; } I've tried it every which way I can think of, firstly using just $title_path, then $GLOBALS['$title_path'] when I thought it was a scope issue, but no luck so far! Any tips or pointers MUCH appreciated! Thanks. Scott Using PHP Version 5.2.13 My question: How do I access a class and it's methods from an included file? I have an Index.php page that calls two methods: <?php get_header(); ?> <?php get_footer(); ?> and it creates a class in an include file <?php include_once($_SERVER['DOCUMENT_ROOT'].'/includes/common.html');?> $site = new WebSite($site_name); // Creates a bunch of properties, defines some methods, etc... $site->initialize(); <?php get_header(); ?> ends up including a another file (header.php) <?php get_header(); ?> ends up including a another file (footer.php) All calls in Index.php to methods in my class work. ie <?php $site->display_section('column'); ?> But calls in either the header.php or footer.php to methods in my class fail with "Call to a member function is not an object". I understand what the error means but I don't understand why. I thought all functions and classes defined in an include file have global scope. As per PHP.NET's documentation: "When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope." The include that creates the class is something that I have inherited from another developer and I actually can't change the scope. I've tried with global $site = new WebSite($site_name);. It actually breaks the entire site. How can I access classes, properties, methods in an include file? Any help would be appreciated. I've been racking my head for several days now on it and it's probably some newbie thing that I am completely overlooking. I hope I've provided enough background and info. Thanks, Brian Well, folks, thanks to all the help, I've narrowed my problem down to needing a way to allow a variable value to traverse into subsequent calls of a function. I have a simple integer - "companyID", and it's set in "actionfile.php" which is called by two forms. The first time it's called by Form A, it's set. I'd LIKE to put it into $_SESSION, but apparently $_SESSION is zeroed out before I can use it in the second call to "actionfile.php" by Form B. A new form/function call is a new session? I've tried setting it to global and static, to no avail. Anything more elegant than writing the value to SQL for later retrieval? Thanks! Mark I have some questions about the scope of navigation : if i define a constant like define('constant'), php manuel says it's global, does this mean that i can use of different files also? like, i defined in define.php and used in anotherfile.php, or shoud the latter file be included then? what about file a.php includes file b.php which in turn includes file c.php. Can functions of a use variables of file c? ultimately: what about variables that are declared global inside a function but this variables is not initialized in that script, like in wordpress: function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) { global $wp_locale; // more code } $wp_locale can be initialized in another script file? thanks in advance Long story short, I have a class that does some data verification and session management. In order to do some of this verification, it needs a database connection. I am using the MDB2 class; here is a sample of the constructor's code: this is a snippet of code from My Class. // FUNCTIONS function __construct() { /* other code here */ // set up our datbase connection global $dsn; // must use global as to include the one *from* the settings.php include $mdb2 =& MDB2::singleton($dsn); if (PEAR::isError($mdb2)) { die("<H1> THERE WAS AN ERROR </H1>" . $mdb2->getMessage()); } echo("SESSION CLASS: if you see this, then we're goood!"); // some very crude debugging, please ignore this! } Now, i have another function within this same class: public static function data_validateUserName($safeUserName){ // build the query $q = "SELECT uName FROM Users WHERE username = '$safeUserName'"; $result = $this->$mdb2->query($q); if($result->numRows() >= 1){ // there is 1 or more hits for a username, it is not available! return false; } else if ($result->numRows() < 1){ // there is less than 1 row with that username, we're golden! return ture; } } Inside the constructor, i have correctly set up a MDB2 object. I was able to run some queries and other things on it *inside* the constructor. Because of this, i know that it's settings are correct and it is fully working. However, when i try to use that $mdb2 object inside this other method, i get all sorts of errors about that being a bad reference to an object that essentially does not exist. Now, i tried searching here, and didn't get much help, so apologies. If you've got a link to a similar question, then please post that with a brief explanation of what you searched for to get it... Also, the php.net manual is not very helpful about the scope of objects in this particular setup... so please know that i did pour over that before posting here. Thanks for your time, all. ***** EDIT ****** I've thought about doing it another way: Each function is passed in a reference to the MDB2 object as an argument instead of relying on the one that is *suposed to be* built in to the actual class it's self. Would this be better / more secure / more efficient?! |