Reputation: 6799
If I run the following PHP code, I get 123. I don't understand the logic behind it. What I think is when I call the function each time it suppose to output 1. So the output should be like 111.
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
}
keep_track();
keep_track();
keep_track();
// output 123
I know that a static variable holds the value even after the function exits but in the above function I am assigning a value in the very first line, yet it still adding +1 with the previous value of $count
.
Could you please explain this? (I am sorry if I sound like a stupid.. but I am trying to find out how exactly this happening)
Upvotes: 2
Views: 114
Reputation: 19888
The code static $count = 0;
is executed once upon compilation which is why with each call of your function the value is not overwritten. See the note "Static declarations are resolved in compile-time." at http://www.php.net/manual/en/language.variables.scope.php
Upvotes: 3