Question

function track_times() {
static $i = 0;
$i++;
static $i = 5;
return $i;
}

echo track_times() . "\n";
echo track_times() . "\n";

The result is:

6
7

I know people don't use static variables in this way, just can't explain the result. The result implies the second assignment takes effect, but $i increments itself before the assignment, so why the first invocation of the function returns 6?

Was it helpful?

Solution

Static declarations are resolved in compile-time. You are incrementing it during runtime. Therefore you are incrementing it after it's already declared as 5. See also http://www.php.net/manual/en/language.variables.scope.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top