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?
When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name. Static variables are initialized only once.
Within a single compilation unit, static variables are initialized in the same order as they are defined in the source (this is called Ordered Dynamic Initialization). Across compilation units, however, the order is undefined: you don't know if a static variable defined in a.
Throughout the program, only one copy of the static member variable is created for the entire class hence static member variables are also called class variables. It is shared by all instances of the class. The static member variable is only visible within the class but its lifetime is till the program ends.
A static variable declaration is only executed once, the first time the function is executed.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With