Using the STATIC STATEMENT
to Remember the Value of a Variable Between Function Calls

Chapter 7 #141 - Martha's CIS 52

ASSIGNMENT/EXPLANATION

"If you declare a variable name within a function in conjuction with the static statement, the variable remains local to the function, and the function "remembers" the value of the variable from execution to execution." (141) This example creates the numberedHeading() function as entirely self-contained. The $num_of_calls variable is declared with the static statement, and then assigned an ititial value when the function is first called. When it is called the second time, to print the words "Doodads", the code remembers the previous value of $num_of_calls (1), increments it, and prints the new value of 2. The real advantage of this method? "You can now paste the numberHeading() function into other scripts without worrying about global variables." (142) Compare this example to the use of a global statement in numberedheading.php

Exercise

1 Widgets

We build a fine range of widgets.

2 Doodads

Finest in the world.

CODE

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