Thursday, June 9, 2016

Saving State Between Function Calls with the static Statement

Local variables within functions have a short but happy life they 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.
Lets 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 below:
<?php
$num_of_calls = 0;
function numberedHeading($txt) {
global $num_of_calls;
$num_of_calls++;
echo "<h1>".$num_of_calls." ".$txt."</h1>";
}
numberedHeading("Mobile Phones");
echo "<p>We build a fine range of mobile phones.</p>";
numberedHeading("Camera");
echo "<p>Also Digital Cameras.</p>";
?>