5.6. Using Static Variables

5.6.1. Problem

You want a local variable to retain its value between invocations of a function.

5.6.2. Solution

Declare the variable as static:

function track_times_called( ) {
    static $i = 0;
    return $i;

5.6.3. Discussion

Declaring a variable static causes its value to be remembered by a function. So, if there are subsequent calls to the function, you can access the value of the saved variable. The pc_check_the_count( ) function shown in Example 5-1 uses static variables to keep track of the strikes and balls for a baseball batter.

In pc_check_the_count( ), the logic of what happens to the batter depending on the pitch count is in the switch statement inside the function. You can instead return the number of strikes and balls, but this requires you to place the checks for striking out, walking, and staying at the plate in multiple places in the code.

While static variables retain their values between function calls, they do so only during one invocation of a script. A static variable accessed in one request doesn't keep its value for the next request to the same page.

5.6.4. See Also

Documentation on static variables at http://www.php.net/language.variables.scope.