How to use static variables in a PHP function

Posted in PHP -

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;
    echo "$index\n";

Calling foo() multiple times like so:


would echo this:


Related posts: