Saving State Between Function Calls with the static Statement
Local variables within functions have a short but happy lifethey come into being when the function is called and die when execution is finished, as they should. Occasionally, however, you may want to give a function a rudimentary memory.
Let's assume that we want a function to keep track of the number of times it has been called so that numbered headings can be created by a script. We could, of course, use the global statement to do this, as shown in Listing 7.8.
Listing 7.8. Using the global Statement to Remember the Value of a Variable Between Function Calls
Put these lines into a text file called numberedheading.php and place this file in your web server document root. When you access this script through your web browser, it should look like Figure 7.6.
Figure 7.6. Using the global statement to keep track of the number of times a function has been called.
This does the job. We declare a variable, $num_of_calls, in line 2, outside the function numberedHeading(). We make this variable available to the function using the global statement in line 4.
Every time numberedHeading() is called, the value of $num_of_calls is incremented (line 5). We can then print out the heading complete with the properly incremented heading number.
This is not the most elegant solution, however. Functions that use the global statement cannot be read as standalone blocks of code. In reading or reusing them, we need to look out for the global variables that they manipulate.
This is where the static statement can be useful. If you declare a variable within a function in conjunction with the static statement, the variable remains local to the function, and the function "remembers" the value of the variable from execution to execution. Listing 7.9 adapts the code from Listing 7.8 to use the static statement.
Listing 7.9. Using the static Statement to Remember the Value of a Variable Between Function Calls
The numberedHeading() function has become entirely self-contained. When we declare the $num_of_calls variable on line 3, we assign an initial value to it. This assignment is made when the function is first called on line 7. This initial assignment is ignored when the function is called a second time on line 9. Instead, the code remembers the previous value of $num_of_calls. We can now paste the numberedHeading() function into other scripts without worrying about global variables. Although the output of Listing 7.9 is exactly the same as that of Listing 7.8, we have made the code a bit more elegant.