PHP Static Properties, Inheritance, and the self k

2019-09-07 22:32发布

问题:

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.