PHP从父节点访问child's和孙子's静态属性


PHP accessing child's and grandchild's static properties from parent

给定以下深度未知的类层次:

class P
{
    protected static $var = 'foo';
    public function dostuff()
    {
        print self::$var;
    }
}
class Child extends P
{
    protected static $var = 'bar';
    public function dostuff()
    {
        parent::dostuff();
        print self::$var;
    }
}
class GrandChild extends Child
{
    protected static $var = 'baz';
    public function dostuff()
    {
        parent::dostuff();
        print self::$var;
    }
}
$c = new GrandChild;
$c->dostuff(); //prints "foobarbaz"

我能在保持功能的同时摆脱dostuff()的重新定义吗?

应该可以了

class P
{
    protected static $var = 'foo';
    public function dostuff()
    {
        $hierarchy = $this->getHierarchy();
        foreach($hierarchy as $class)
        {
            echo $class::$var;
        }
    }
    public function getHierarchy()
    {
        $hierarchy = array();
        $class = get_called_class();
        do {
            $hierarchy[] = $class;
        } while (($class = get_parent_class($class)) !== false);
        return array_reverse($hierarchy);
    }
}
class Child extends P
{
    protected static $var = 'bar';
}
class GrandChild extends Child
{
    protected static $var = 'baz';  
}
$c = new GrandChild;
$c->dostuff();