Showing posts with label static. Show all posts
Showing posts with label static. Show all posts

Saturday, June 18, 2016

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





<?php
function numberedHeading($txt) {
static $num_of_calls = 0;
$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>";
?>

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.

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>";
?>