【问题标题】:PHP accessing child's and grandchild's static properties from parentPHP从父级访问子级和孙级的静态属性
【发布时间】:2014-03-11 00:03:07
【问题描述】:

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

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() 的重新定义吗?

【问题讨论】:

  • 你是什么意思摆脱重新定义?预期的输出是多少?
  • 输出完全不会改变。我想避免在每个子类中重新定义 dostuff() 方法,从而重复代码。
  • 但是当你打印时你想要的输出是“baz”或“foo”?
  • 啊,好吧,我知道你看到了评论,让我想想..

标签: php static parent self


【解决方案1】:

应该这样做

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

【讨论】:

  • 将函数 getHierarchy 编辑为更简洁
猜你喜欢
  • 2021-11-05
  • 1970-01-01
  • 2011-03-29
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多