8.5 Retaining a Variable's Value Between Function Calls
TechniqueUse the static statement to have PHP remember the value of the variable from the last function call: function sequence_get_next_value() { static $x = 0; return $x++; } print sequence_get_next_value (); #prints 0 print sequence_get_next_value (); #prints 1 print sequence_get_next_value (); #prints 2 CommentsThe static statement is an elegant way to avoid using global variables in your function. It remembers the value of $x from function call to function call for the amount of time that the PHP script executes. This means that after the script execution is complete, PHP forgets about the value of the static variable. |