PHP Tutorial - PHP static variable






Static variables are still local to a function, they can be accessed only within the function's code. Unlike local variables, which disappear when a function exits, static variables remember their values from one function call to the next.

Syntax

To declare a local variable as static, all you need to do is write the word static before the variable name, and assign an initial value to the variable:

 
static $var = 0;  

Note

The first time the function is called, the variable is set to its initial value.

If the variable's value is changed within the function, the new value is remembered the next time the function is called. The value is remembered only as long as the script runs, so the next time you run the script the variable is reinitialized.





Example

static variable


<?PHP//from   w  ww  .  ja va2s . c o  m
        function nextNumber() { 
          static $counter = 0; 
          return ++$counter; 
        } 

        echo "I've counted to: " . nextNumber() . "\n"; 
        echo "I've counted to: " . nextNumber() . "\n"; 
        echo "I've counted to: " . nextNumber() . "\n";   
?>

The code above generates the following result.