Page 191 - Beginning PHP 5.3
P. 191
Chapter 7: Functions
In this script, the setup() function is called first. It declares the $myGlobal variable as global, and gives
it a value. Then the hello() function is called. It too declares $myGlobal to be global, which means it
can now access its value — previously set by setup() — and display it.
By the way, you can also declare more than one global variable at once on the same line — just separate
the variables using commas:
function myFunction() {
global $oneGlobal, $anotherGlobal;
}
Finally, you can also access global variables using the $GLOBALS array. This array is a special type of
variable called a superglobal , which means you can access it from anywhere without using the global
statement. It contains a list of all global variables, with the variable names stored in its keys and the
variables ’ values stored in its values. Here ’ s an example that uses $GLOBALS :
$myGlobal = “Hello there!”;
function hello() {
echo $GLOBALS[“myGlobal”] . “ < br/ > ”;
}
hello(); // Displays “Hello there!”
The hello() function accesses the contents of the $myGlobal variable via the $GLOBALS array. Notice
that the function doesn ’ t have to declare the $myGlobal variable as global in order to access its value.
PHP makes other superglobal variables available to you as well. You study superglobals in more depth
in Chapter 9 .
Be careful with global variables. If you modify the value of a global variable in many different places
within your application, it can make it hard to debug your code when something goes wrong. Generally
speaking, you should avoid using global variables unless it ’ s strictly necessary.
Using Static Variables to Preserve Values
As you ’ ve seen, variables that are local to a function don ’ t exist outside the function. In fact, all variables
declared within a function are deleted when the function exits, and created anew when the function is
next called. This is usually what you want to happen, because it allows you to write nicely self - contained
functions that work independently of each other.
However, sometimes it ’ s useful to create a local variable that has a somewhat longer lifespan. Static
variables let you do just this. These types of variables are still local to a function, in the sense that they can
be accessed only within the function ’ s code. However, unlike local variables, which disappear when a
function exits, static variables remember their values from one function call to the next.
To declare a local variable as static, all you need to do is write the word static before the variable
name, and assign an initial value to the variable:
static $var = 0;
153
9/21/09 9:00:55 AM
c07.indd 153
c07.indd 153 9/21/09 9:00:55 AM