Sometimes you want to give a function a "rudimentary memory". For instance, you may want "a function to keep track of the number of times it has been called so that numbered headins can be created by a script." (140) The script seen on this page does just that - the variable $num_of_calls is declared outside the function, and then made available to the function itself by use of the global statement. "Every time numberedHeading() is called, the value of $num_of_calls is incremented...You can then print out the heading complete with the properly incremented heading number." (141) However, there are some drawbacks to this approach. #1, it's not the most elegant way to achieve this solution. More than that, #2, "Functions that use the global statement cannot be read as standalone blocks of code." The danger is that "In reading or reusing them, we need to look out for the global variables that they manipulate." A better solution, in this case, may be use of the static statement: numberedheading2.php.
We build a fine range of widgets.
Finest in the world.
<?php
$num_of_calls = 0;
function numberedHeading($txt) {
global $num_of_calls;
$num_of_calls++;
echo "<h1>".$num_of_calls." ".$txt."</h1>";
}
numberedHeading("Widgets");
echo "<p>We build a fine range of widgets.</p>";
numberedHeading("Doodads");
echo "<p>Finest in the world.</p>";
?>