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
But I expect it to be the following:
here is a: null
here is a: 100
It's hard to believe that the output you indicate is really the output of that code. Yet the problem is clear here:
A static variable is bound to a function or class and declared via the static keyword. You are re-declaring $a; this should (I guess) raise a warning.
As static properties 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 $a is assigned the value of 23. After the first echo statement.
This is a 2-step process, first the parser will read the function's definition, including static properties. After that the code will run, and the properties are mutated.
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