PHP Static Variables PHP Static Variables php php

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 = 5function 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.


You have two separate variables that are both called $count, but they have a different scope.The first variable is not explicitly declared, but comes into existence when you first assign it.

The second variable (inside the method) is only visible to that method. Since it's static, its value is retained between multiple executions of the same method. The assignment $count = 0; is only executed the first time the method is run.

As for the increment operator (++), the result of the evaluation is the value before it was incremented, because the (unary) operator comes after the variable name. So yes, the output would be 5, 0, 1.
If you were to write return ++$count;, the result would have been 5, 1, 2.

Note: the ++$count you have in your existing code, it is effectively equivalent to $count++, since the result of the evaluation is discarded. The effect to the $count variable is the same: it gets incremented by 1.