How to use static variables in a PHP function
Posted January 9th, 2012 in PHP (Updated January 24th, 2012)
There may be times when a static variable is needed in a PHP function; static variables maintain their value between function calls and are tidier than using a global variable because they cannot be modified outside of the function. (If the function is contained within a class, you may be better using a private or protected class variable instead of a static variable inside the function).
PHP code example
The PHP code example below shows a function which uses a static variable. When the function is first called it won't have a value set so it's initialized with the = 0 bit and then incremented on each subsequent call. Note that it doesn't need to be an integer; any type should work just fine.
The echo $index line is to show the example working.
function foo() {
static $index = 0;
$index++;
echo "$index\n";
}
Calling foo() multiple times like so:
foo(); foo(); foo();
would echo this:
1 2 3
Related posts:
- Multiple variable assignment with PHP (Monday, December 14th 2009)
- How to use static variables in a Javascript function (Tuesday, September 29th 2009)

Comments
blog comments powered by Disqus