class A
{
static $v = "A";
static function echoExtendedStaticVariable() {
echo self::$v;
}
}
class B extends A
{
static $v = "B";
// override A's variable with "B"
}
Why does:
echo B::$v
print “A”?
And how do I get it to print “B”?
Is there a way to do this before PHP 5.3?
B->echoExtendedStaticVariable() == 'A'becauseself::is evaluated at compile-time, not run-time. It’s as if you wroteA::instead ofself::.What you want is a feature called “late static binding”–it’s “late” because it can determine the class at runtime instead of at compile-time.
You can emulate this (sort-of) in PHP 5.2 using
ReflectionClass:Note that you can only do this if you have access to an instance, so you can’t make
echoExtendedStaticVariablea static method and expect this to work.