Using the static Statement to Remember the Value of a Variable Between Function Calls

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

function numberedHeading($txt) {
static $num_of_calls = 0;
echo "<h1>".$num_of_calls." ". $txt."</h1>"; }
numberedHeading("Mobile Phones");
echo "<p>We build a fine range of mobile phones.</p>";
echo "<p>Also Digital Cameras..</p>";

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.

No comments: