繁体   English   中英

PHP从父级访问子级和孙级的静态属性

[英]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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM