Showing posts with label global. Show all posts
Showing posts with label global. Show all posts

Friday, May 20, 2016

Accessing Variables with the global Statement

From within one function, you cannot (by default) access a variable defined in another function or elsewhere in the script. Within a function, if you attempt to use a variable with the same name, you will only set or access a local variable. Lets put this to the test :
<?php
$life = 42;
function meaningOfLife() {
echo "The meaning of life is ".$life;
}
meaningOfLife();
?>
Put these lines into a text file called scopetest2.php and place this file in your web server document root. When you access this script through your web browser, it should look like:




As you might expect, the meaningOfLife() function does not have access to the $life variable in line 2; $life is empty when the function attempts to print it. On the whole, this is a good thing because it saves us from potential clashes between identically named variables, and a function can always demand an argument if it needs information about the outside world. Occasionally, you may want to access an important variable from within a function without passing it in as an argument. This is where the global statement comes into play. Use global to restore order to the universe.
<?php
$life=42;
function meaningOfLife() {
global $life;
echo "The meaning of life is ".$life;
}
meaningOfLife();
?>
Put these lines into a text file called scopetest3.php and place this file in your web server document root. When you access this script through your web browser, it should look like:




By placing the global statement in front of the $life variable when we declare it in the meaningOfLife() function (line 4), it now refers to the $life variable declared outside the function (line 2).
You will need to use the global statement within every function that needs to access a particular named global variable. Be careful, though; if you manipulate the contents of the variable within the function, the value of the variable will be changed for the script as a whole.
You can declare more than one variable at a time with the global statement by simply separating each of the variables you want to access with commas:
global $var1, $var2, $var3;


Watch Out!
Usually, an argument is a copy of whatever value is passed by the calling code; changing it in a function has no effect beyond the function block. Changing a global variable within a function, on the other hand, changes the original and not a copy. Use the global statement carefully.