Page 192 - Beginning PHP 5.3
P. 192
Part II: Learning the Language
The first time the function is called, the variable is set to its initial value (zero in this example). However,
if the variable ’ s value is changed within the function, the new value is remembered the next time the
function is called. The value is remembered only as long as the script runs, so the next time you run
the script the variable is reinitialized.
So when might you use static variables? Here ’ s a situation where a local variable isn ’ t much use:
function nextNumber() {
$counter = 0;
return ++$counter;
}
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
This code outputs the following:
I’ve counted to: 1
I’ve counted to: 1
I’ve counted to: 1
Each time the nextNumber() function is called, its $counter local variable is re - created and initialized
to zero. Then it ’ s incremented to 1 and its value is returned to the calling code. So the function always
returns 1, no matter how many times it ’ s called.
However, by making a small change to turn $counter into a static variable, the script produces the
expected output:
function nextNumber() {
static $counter = 0;
return ++$counter;
}
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
echo “I’ve counted to: “ . nextNumber() . “ < br/ > ”;
Now the code displays:
I’ve counted to: 1
I’ve counted to: 2
I’ve counted to: 3
You probably won ’ t use static variables that often, and you can often achieve the same effect (albeit with
greater risk) using global variables. However, when you do really need to create a static variable you ’ ll
probably be thankful that they exist. They ’ re often used with recursive functions (which you learn about
later in this chapter) to remember values throughout the recursion.
Creating Anonymous Functions
PHP lets you create anonymous functions — that is, functions that have no name. You might want to
create anonymous functions for two reasons:
154
9/21/09 9:00:55 AM
c07.indd 154 9/21/09 9:00:55 AM
c07.indd 154