how to get to parent overridden property from child?

强颜欢笑 提交于 2021-01-27 20:26:02

问题


in the php documentation it says:

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

i get an error when i try to access overridden (not static) parent properties:

class foo
{
    public $bar = 'foobar';
}

class baz extends foo
{
    public $bar = 'bazbar';

    public function get_bar()
    {
        echo parent::$bar; //Fatal error:  Access to undeclared static property: foo::$bar
    }
}

$baz = new baz;
$baz->get_bar();

回答1:


Fisrt, use :: with static properties, not instance properties.
Second, though you can do it with Reflection(see the following code), I don't see any point accessing parent instance properties, that's polymorphism is for.

class foo
{
    public $bar='foobar';
}
class bar extends foo
{
    public $bar='bazbar';
    function get_bar()
    {
        $thisClass = new ReflectionClass($this);
        $parentClass = $thisClass->getParentClass();
        $props = $parentClass->getDefaultProperties();
        return $props['bar'];
    }
}

$b = new bar();
echo $b->get_bar(); // foobar



回答2:


class foo
{
  public $bar = 'foobar';
}

Make $bar static variable. You can access static member variable, function using resolution operator(::)



来源:https://stackoverflow.com/questions/19674425/how-to-get-to-parent-overridden-property-from-child

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!