8.5 Retaining a Variable s Value Between Function Calls


8.5 Retaining a Variable's Value Between Function Calls

You want a variable to retain its value between function calls.

Technique

Use 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 

Comments

The 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.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net