Static Inheritance prior to PHP 5.3

前提是你 提交于 2019-12-10 18:06:29

问题


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?


回答1:


B->echoExtendedStaticVariable() == 'A' because self:: is evaluated at compile-time, not run-time. It's as if you wrote A:: instead of self::.

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:

class A
{
    static $v = "A";
    function echoExtendedStaticVariable() {
        $rc = new ReflectionClass($this);
        echo $rc->getStaticPropertyValue('v');
    }
}
class B extends A
{
    static $v = "B";
}
$b = new B();
$b->echoExtendedStaticVariable(); // B

Note that you can only do this if you have access to an instance, so you can't make echoExtendedStaticVariable a static method and expect this to work.




回答2:


There is no way to do this easily in PHP 5.2 (i.e.: without explicitly overriding each method).

When you call B::echoExtendedStaticVariable, it forwards to A::echoExtendedStaticVariable, the scope changes to the one of A and all bindings about B are gone. No backtrace, no reflection, no magic constants, nothing: it all points to A.

In my opinion, static members should be avoided unless really necessary, and it is rarely the case. It renders your code difficult to extend, since dependency injection is limited and substitution is almost impossible (except in anti- patterns like Singleton).



来源:https://stackoverflow.com/questions/8581435/static-inheritance-prior-to-php-5-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!