How can the parent be replaced by a child?

advertisements

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


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