PHP Static Properties, Inheritance, and the self keyword

自作多情 提交于 2019-12-11 15:34:33

问题


This doesn't make sense to me:

class A {
    public static $value = "a";
    public static function get_value(){
        return self::$value;
    }
}

echo A::$value;       // a, this makes sense
echo A::get_value();  // a, this makes sense

class B extends A {
    public static $value = "b";
}

echo B::$value;       // b, this makes sense
echo B::get_value();  // a?  :(

Why doesn't the self pointer work as expected, similar to this? Is there another keyword that could be used to accomplish this?

If I add the static function to class B, it now works as expected.

class B extends A {
    public static $value = "b";
    public static function get_value(){
        return self::$value;
    }
}

echo B::get_value();  // b  :)

If the method contained more than 1 line, it wouldn't make sense to copy+paste this functionality and manage it in 2 locations...


回答1:


Late Static binding:

http://php.net/manual/en/language.oop5.late-static-bindings.php

late static bindings work by storing the class named in the last "non-forwarding call".

try using static:: keyword instead of self:: in your example.



来源:https://stackoverflow.com/questions/20035666/php-static-properties-inheritance-and-the-self-keyword

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