Page 190 - Beginning PHP 5.3
P. 190
Part II: Learning the Language
Consider what would happen if the scope of the $color variable was not limited. In this case, $color
would first be set to “ black ” as before:
// Define my cat
$color = “black”;
However, when the describeMyDog() function was then called, it would overwrite the $color variable
with the value “ brown ” (because there ’ s only one $color variable), producing the following output:
My dog is brown
My cat is brown
So variable scope avoids clashing variable names, which helps to prevent you accidentally overwriting
variables of the same name. This is another reason why functions are so good.
Working with Global Variables
Although the concept of variable scope is extremely useful, occasionally you do actually want to create
a variable that can be accessed anywhere in your script, whether inside or outside a function. Such a
variable is called a global variable .
PHP supports global variables, but if you ’ re used to other programming languages you ’ ll find PHP
handles globals slightly differently.
In PHP, all variables created outside a function are, in a sense, global in that they can be accessed by any
other code in the script that ’ s not inside a function. To use such a variable inside a function, write the
word global followed by the variable name inside the function ’ s code block. Here ’ s an example:
$myGlobal = “Hello there!”;
function hello() {
global $myGlobal;
echo “$myGlobal < br/ > ”;
}
hello(); // Displays “Hello there!”
You can see that the hello() function accesses the $myGlobal variable by declaring it to be global using
the global statement. The function can then use the variable to display the greeting.
In fact, you don ’ t need to have created a variable outside a function to use it as a global variable. Take a
look at the following script:
function setup() {
global $myGlobal;
$myGlobal = “Hello there!”;
}
function hello() {
global $myGlobal;
echo “$myGlobal < br/ > ”;
}
setup();
hello(); // Displays “Hello there!”
152
9/21/09 9:00:55 AM
c07.indd 152 9/21/09 9:00:55 AM
c07.indd 152