I got this example when working with static scope in PHP function:
function testStatic() {
static $a;
echo "here is a first time: ".$a."<br />";
$a = 23;
static $a = 100;
echo "here is a second time: ".$a."<br />";
}
when I run this function like this
teststatic(); echo "<hr />";
teststatic();
It output result below:
here is a: 100
here is a: 23
here is a: 23
here is a: 23
But I expect it to be the following:
here is a: null
here is a: 100
here is a: 100
here is a: 100
I have been thinking hours try to explain why I received the result above but really failed.
Could you tell me why we have the result above? Thank you!
It’s hard to believe that the output you indicate is really the output of that code. Yet the problem is clear here:
A
staticvariable is bound to a function or class and declared via thestatickeyword. You are re-declaring$a; this should (I guess) raise a warning.As
staticproperties are part of the function’s or class’ definition, (apparently) the last occurrence of it will be “attached” to the function/class in question.Only the first time the function is called
$ais assigned the value of23. After the firstechostatement.This is a 2-step process, first the parser will read the function’s definition, including
staticproperties. After that the code will run, and the properties are mutated.