PHP - Global Variable Scope And Duration
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? Similar Tutorials<?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. Good morning! I've spent hours on this to no avail. My understanding is that unset() only deletes the copy of the variable local to the current scope. But I am getting a very different result. I have the following structure and output. What am I doing wrong? <?php first_function(); second_function() { for ($count = 0; $count < $max; $count++) { $my_array = array[]; //initialize my array, local in this scope but can be called global in nested functions print_r($my_array ); //print 1: array should be always empty but is only in empty in FIRST loop. third_function(); //fills the array with numbers, see below, nested function declaring a global array print_r($my_array ); //print 3 of my_array, should be full of numbers from third_function global changes unset($my_array); //delete my array so I can start with new array in next loop print_r($my_array ); //print 4 of my_array, should be unknown variable print('End one loop'); } } third_function() { global $my_array; //declare my global variable //...fill my now global array with stuff... print_r($my_array ); //print 2: should be filled with numbers. And it is. } ?> My output amazingly looks something like this Array() Array(45,48,38...all my numbers...) Array() ERROR: Notice -- Undefined variable: my_array End one loop Array(45,48,38...all my SAME numbers again as if array was NOT unset...) ...... The first and second print lines make sense. But shouldn't the third line be the array filled with numbers generated in third_function? The fourth line error makes sense as the variable is unset. But WHAT did I unset? The next time around in the loop, the array contains the SAME numbers from the previous loop and my new numbers simply get appended to the end of the ever growing array. Why? This should not be that difficult but seems to be driving me crazy. Any help would be greatly appreciated. alexander 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 is 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 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 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 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 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! 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? 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? ok iv set up a simple demo this is the code im running include('simple_html_dom.php'); include('config.php'); include('connect.php'); include('functions.php'); include($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'globalFunctions.php'); test(); echo "test variable = ".$test; exit; this is the function which is in globalFunctions.php which is two directories back ../../ function test() { $test = 10; global $test; } how come when i run script i am not getting variable echoed Sorry, this will be a simple question. Say you define two global variables in your functions.php file as: GLOBAL $salesTax = .07; GLOBAL $shipping = 5.00; Those variables would be accessiible in the checkout.php page, right? Hi All, For the last post,I m very happy that i found out so many great mind who are watching my problem and solving online. anyway great thanks for all, just now i m making a project and i m facing problem in the below code "i need to know how can make this code easy or how can i make rdata variable accessible for the download button" generatecv.php file <?php if(isset($_REQUEST['submit'])) { $name=$_REQUEST['pname']; $pin=$_REQUEST['pin']; $mnumb=$_REQUEST['mnumber']; $tnumb=$_REQUEST['telenumber']; $email=$_REQUEST['email']; $obj=$_REQUEST['obj']; $title=$_REQUEST['jobt']; $activity=$_REQUEST['activity']; //$file=fopen('test.doc','a+'); //echo @fwrite($file,$name); //fclose($file); $rdata=""; $rdata.="<table id='cvtbl' border='0' align='center' > <th>Resume</th> <tr><td>".$name.":</td></tr><tr><td>Objective:</td></tr>"; $rdata.="<tr><td>".$obj."</td></tr>"; $rdata.="<tr><td>Email:".$email."</td></tr>"; $rdata.="</table>"; echo $rdata; echo "<style>#cv{display:none;}</style>"; echo "<form><input type='submit' name='dwnld' id='dwnld' value='Download'/></form>"; } if(isset($_REQUEST['dwnld'])) { header("Content-type:application/msword"); header("Content-disposition:attachment;filename=test.doc"); $fp=fopen("test.doc","r") or die("try again"); $data=fread($fp,filesize('test.doc')); fwrite($fp,$rdata); echo $data; fclose($fp); //echo $rdata."<br />".$rdata; } ?> this is the html file <html> <title>User details</title> <body> <form name='cv' id='cv' method="post" enctype="multipart/form-data" action='generatecv.php'> Enter your name<input type=text name=pname id=pname /> Zip Code<input type=text name=pin id=pin /> Mobile number<input type=text name=mnumber id=mnumber /> <br />Telephone number <input type=text name=telenumber id=telenumber /> Email address<input type=text name=email id=email /> <br />Enter your objective<br /><textarea name=obj id=obj cols=30 rows=5 ></textarea> <!--University Name <input type=text name=university id=university /> --> <br /><!--uni, city ,state ,type of degree ,full degree name,date--> <br /><!--Experience<br /><textarea name=exp id=exp cols=30 rows=5 ></textarea> --> Select type of resume <select name='type' id='type' onChange=''> <option value='0'>Graduate</option> <option value='1'>Post Graduate</option> <option value='2'>Non Graguate</option> <option value='3'>Other</option> </select> Job title<input type='text' name='jobt' id='jobt' /> <br /><!--company name,city ,state ,office number ,job description ,date of employment--> <br />Activity <input type=text name=activity id=activity size=100 /> <br />Honors/Awards<input type=text name=honor id=honor size=100 /> <input type='submit' name='submit' id='submit' value='Generate CV' /> <input type='reset' name='Reset' id='submit' value='Reset' /> </form> </body> </html> Many thanks in advance I run these functions to find the key of a given element inside an array. Like so; $ban_ip_file = file("ip_file.txt"); foreach($ban_ip_file as $key => $value) { $value = trim($value); if($value == $ip_from_form)// passed to page by a form $set = $key; } How do I make $set available for testing and file writing further down the script? Tried assigning global $set; just above the $set=$key; ----but it did not work. I declared a variable in a page. When i want to access that variable in other page i am bound to state as global such as global $var; now i can not access this variable in other pages even if declared global. Please some one tell me how to declare a variable once and can use in any page i want. Hi guys, I'm new to this forum and hope this is the right place to post this question. I run an internet radio station using SAM Broadcaster. I am trying to display the duration of the song on my main page without the front zero (see enclosed picture): I want the duration to display like this: example (5:47) instead of with the front zero (05:47) Here is a snipet of the code I think it needs to be changed in here somewhe
<td><?php echo preg_replace("/[^!<>@&\/\sA-Za-z0-9_]/","", $row['title']); ?><br><a href="javascript:void(0);" class="album"><strong><?php echo preg_replace("/[^!<>@&\/\sA-Za-z0-9_]/","", $row['artist']); ?></strong></a> (<?php echo date('i:s',$row['duration'] / 1000); echo $duration[0] === '0' ? substr($duration, 1) : $duration; ?>)<div class="albuminfo"> Hello........ Currently i am struggling with php script....... can any one tell me or guide me how to code Automatically generating random number with in the range of 19 to 90 and the number has to change with in 24 hours time duration......... It's urgent........ Thanks in advance..... Rooban.S Other than if statement, is there a way to change a duration give in seconds (e.g. 5746 seconds) to the standard format of x hours and y minutes and z seconds? 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. |