PHP访问子';s和孙子孙女';来自父对象的静态属性

PHP访问子';s和孙子孙女';来自父对象的静态属性,php,static,parent,self,Php,Static,Parent,Self,给定以下一般未知深度的类层次结构: class P { protected static $var = 'foo'; public function dostuff() { print self::$var; } } class Child extends P { protected static $var = 'bar'; public function dostuff() { parent::do

给定以下一般未知深度的类层次结构:

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();

你说摆脱重新定义是什么意思?预期的输出是什么?输出应完全不变。我希望避免在每个子类中重新定义dostuff()方法,从而重复代码。但是打印时,您希望的输出是“baz”或“foo”?啊,好吧,我知道您看到了注释,让我想想..编辑函数getHierarchy使其更干净