Hello, everybody.
While working with static variables inside static class' methods, I have
found this very interesting (at least for me) behavior of PHP.
Consider the following class definitions (example #1):
class X {
public final static function test() {
static $i;
return ++$i;
}
}
class Y extends X {
}
By executing this code:
echo X::test();
echo Y::test(); // note Y class here
one would expect to see "12" as output, but apparently I get "11".
That's a bit confusing if you logically assume that "static vars" are "tied
to the scope" they're defined in. Since this static variable is
defined in a specific static method test(), that is NOT overloaded by class
Y, in my opinion it shoul've preserved it's value across static calls.
Let's look at another example (example #2):
class X {
public static $x =0;
public final static function test() {
return ++static::$x; // note static keyword here
}
}
class Y extends X {
}
If you run this code:
echo X::test();
echo Y::test();
you get "12" as output - the expected output. Notice that the "++static::$x"
expr. is taking advantage of late static binding. Now, if you change
body of test() to the following code:
public final static function test() {
return ++self::$x;
}
then you also get "12" as output.
Is this a bug that static context of $i is not preserved in example #1 or do
I misunderstand something?
I could not find any hints on this in the PHP documentation.
Dmitry.