簡體   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