PHP Static Variables

The variable $count in the function is not related in any kind to the global $count variable. The static keyword is the same as in C or Java, it means: Initialize this variable only once and keep its state when the function ends. This means, when execution re-enters the function, it sees that the inner $count has already been initialized and stored the last time as 1, and uses that value.


$count = 5; // "outer" count = 5

function get_count()
{
    static $count = 0; // "inner" count = 0 only the first run
    return $count++; // "inner" count + 1
}

echo $count; // "outer" count is still 5 
++$count; // "outer" count is now 6 (but you never echoed it)

echo get_count(); // "inner" count is now + 1 = 1 (0 before the echo)
echo get_count(); // "inner" count is now + 1 = 2 (1 before the echo)
echo get_count(); // "inner" count is now + 1 = 3 (2 before the echo)

I hope this clears your mind.

Tags:

Php

Static