PHP - Proper Use Of Globals And Variable Scope
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? Similar TutorialsIn 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 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 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 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'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? Almost every time when I read about globals, programmers discourage their use. I have a function where I need to send back some variables (which I will use in a query) so I need to use globals. Below is the function and query. I'm trying to figure out if it's ok to use globals in it. function paginate($connection, $tableName) { //the forsaken globals global $limit; global $start; //Pagination $targetpage = "http://localhost/website/untitled2.php"; $limit = 4; //count rows $sql = "SELECT COUNT(*) as num FROM $tableName"; $total_pages = $connection->query($sql) or die(mysqli_error($connection)); $row = $total_pages->fetch_assoc(); $total_pages = $row['num']; //if there's no page number, set it to the first page $stages = 3; $page = isset($_GET['page']) ? $_GET['page'] : 0; $start = empty($page) ? 0 : ($page - 1) * $limit; // Initial page num setup if ($page == 0){$page = 1;} $prev = $page - 1; $next = $page + 1; $lastpage = ceil($total_pages/$limit); $LastPagem1 = $lastpage - 1; $paginate = ''; if($lastpage > 1) { $paginate .= "<div class='paginate'>"; // Previous if ($page > 1){ $paginate.= "<a href='$targetpage?page=$prev'>previous</a>"; }else{ $paginate.= "<span class='disabled'>previous</span>"; } // Pages if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few? { // Beginning only hide later pages if($page < 1 + ($stages * 2)) { for ($counter = 1; $counter < 4 + ($stages * 2); $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // Middle hide some front and some back elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2)) { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $page - $stages; $counter <= $page + $stages; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>"; } // End only hide early pages else { $paginate.= "<a href='$targetpage?page=1'>1</a>"; $paginate.= "<a href='$targetpage?page=2'>2</a>"; $paginate.= "..."; for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";} } } } // Next if ($page < $counter - 1){ $paginate.= "<a href='$targetpage?page=$next'>next</a>"; }else{ $paginate.= "<span class='disabled'>next</span>"; } $paginate.= "</div>"; } echo $total_pages.' Results'; // pagination echo $paginate; }//end function and this is how I'm using the function. Without the globals I would get undefined vars $start and $limit used in the query below. paginate($connection, "categories"); $sql = "SELECT * FROM categories ORDER BY cat_name LIMIT $start, $limit"; $cats_result = $connection->query($sql) or die(mysqli_error($connection)); while ($row = $cats_result->fetch_assoc()) { $cat_id = $row['cat_id']; $cat_name = $row['cat_name']; $cat_desc = $row['cat_desc']; ...etc Am I using the globals properly? Has anyone encountered this bug which had me banging my head against the desk all morning? In the beginning I registered a $GLOBALS['direction'] that equalled to a radio button value. Later in the script I declare a variable $direction that for some strange reason took the value of $GLOBALS['direction'] without me even writing so. So when i compared them they had the same value. As soon as I changed $direction to $directionx the script worked and the value wasn't "copied" to the $GLOBALS. What's up? What does this mean? Code: [Select] {$GLOBALS['path']} I WANT TO MAKE AN ARRAY LIKE $GLOBALS structu if you run var_dump($GLOBALS): you will see that this is an array and contains another 9 array with key names. when there is a value(name) in "_POST" you cant use echo $GLOBALS["name"]. but when there is a value("fname") in "GLOBALS" you can use echo $GLOBALS["fname"]. how this array works like that? and how to make an array that behave like that? Edited January 17, 2020 by Silent-BWell I heard that registering $GLOBALS is a bad practice in general since their values can be changed by anyone at anytime. However, the usage of $GLOBALS does simplify the script considerably at times when a certain column in a table needs to be retrieved repeatedly. A good example is user's money data stored in table prefix_users as shown below: Code: [Select] $result = mysql_query( "SELECT * FROM {$prefix}users WHERE uid = '$uid'"); $GLOBALS['usersettings'] = mysql_fetch_array($result); $GLOBALS['money'] = $GLOBALS['usersettings']['money']; If the above code is included in a function file, it will be possible to simply use $GLOBALS['money'] to retrieve user's money data without having to write lines of mysql commands everytime. So I was wondering, is there another way to retrieve database info from a certain column easily but not to register $GLOBALS? Just curious. This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=356029.0 I'm learning functions and I'm working on a rating script. This is a small test script that works, you can try it out yourself: <?php // Rating System function while_test (){ $a = 1; $b = 4; $t_id = 1; global $likes; global $dislikes; global $con_id; while ($a++ <= $b){ echo "<center>"; echo "<table><tr><td>Table: </td></tr>"; echo "<tr><td>This is a table test </td></tr>"; echo "<tr><td><form action='' method='post'>"; echo "<button type='submit' name='likes' value='Y'>likes</button>"; echo "<button type='submit' name='dislikes' value='N'>dislikes</button>"; echo "<input type='hidden' name='hidden_id' value='" . $t_id . "' /></form></td></tr></table>"; echo "</center><br /><br />"; $t_id++; $likes = $_POST['likes']; $dislikes = $_POST['dislikes']; $con_id = $_POST['hidden_id']; } } while_test(); if ($likes) { echo "likes it: " . $likes . " con_id: " . $con_id; } elseif ($dislikes) { echo "dislikes it: " . $dislikes . " con_id: " . $con_id; } ?> I've gotten recommended before not use globals, because the projects would become unmanageable, and I'm wondering how would I be able to avoid using globals in this example? I'm able to in-ject variables through the parenthesis, but I'm not able to out-ject variables, if that makes sense. (?) At least it doesn't work for me. How would I use those three variables $likes, $dislikes and $con_id outside the function without setting them as globals, what would be good practice? Learning something new here so if anyone can tell me why I this wont return a value? page1.php Code: [Select] <?php require "page2.php"; getuserid(); echo $userID; ?> page2.php Code: [Select] <?php function getuserid() { $user =& JFactory::getUser(); $userID = $user->id; global $userID; } ?> Hi I'm currently experiencing problems with my super global outputs.
I'm using
$_SERVER['HTTP_X_MXIT_NICK']; I have been trying to better understand how php works on a more in depth level, and recently I have been tinkering with arrays. Using print_r() I have been studying the $GLOBAL array, and I found something I can't seem to find an explanation for. In my $GLOBALS array there are variables I have set in a configuration file, but never actually made into globals. Take the following code, and its output for example. echo "<pre>"; echo print_r($GLOBALS); echo "</pre>"; The output: Code: [Select] Array ( [GLOBALS] => Array *RECURSION* [_POST] => Array ( ) [_GET] => Array ( ) [_COOKIE] => Array ( [PHPSESSID] => fai4rtfgdt6o6iaihh62d0pa15 ) [_FILES] => Array ( ) [_SERVER] => Array ( [HTTP_HOST] => DOMAIN [HTTP_USER_AGENT] => Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [HTTP_ACCEPT_LANGUAGE] => en-us,en;q=0.5 [HTTP_ACCEPT_ENCODING] => gzip,deflate [HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.7 [HTTP_KEEP_ALIVE] => 115 [HTTP_CONNECTION] => keep-alive [HTTP_REFERER] => http://DOMAIN/test.php [HTTP_COOKIE] => PHPSESSID=fai4rtfgdt6o6iaihh62d0pa15 [HTTP_CACHE_CONTROL] => max-age=0 [CONTENT_TYPE] => application/x-www-form-urlencoded [CONTENT_LENGTH] => 67 [PATH] => /sbin:/usr/sbin:/bin:/usr/bin [SERVER_SIGNATURE] => [SERVER_SOFTWARE] => Apache [SERVER_NAME] => DOMAIN [SERVER_ADDR] => IPADDRESS [SERVER_PORT] => 80 [REMOTE_ADDR] => 198.65.168.24 [DOCUMENT_ROOT] => /home/USER/www/DOMAIN [SERVER_ADMIN] => webmaster@DOMAIN [SCRIPT_FILENAME] => /home/USER/www/DOMAIN/test.php [REMOTE_PORT] => 43272 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => POST [QUERY_STRING] => [REQUEST_URI] => /test.php [SCRIPT_NAME] => /test.php [PHP_SELF] => /test.php [REQUEST_TIME] => 1286050077 ) [date] => October 2, 2010 [db_date] => 10/02/2010 [error] => Array ( ) ) 1 The 3 items at the bottom. Code: [Select] [date] => October 2, 2010 [db_date] => 10/02/2010 [error] => Array Were set inside of a php config file. My question is, how did they end up in the $GLOBALS array? HI! Can someone explain the variables $value and $key that are being produced at the end of the output by the following code. It seems like the foreach loop is creating two extra variables. <?php $test_1 = "matt"; $test_2 = "kim"; $test_3 = "jessica"; $test_4 = "keri"; foreach ($GLOBALS as $key => $value) { echo $key . "- - -" . $value; echo "<br />"; } ?> Output GLOBALS- - -Array _POST- - -Array _GET- - -Array _COOKIE- - -Array _FILES- - -Array test_1- - -matt test_2- - -kim test_3- - -jessica test_4- - -keri value- - -keri key- - -value Thanks! steadythecourse |