问题
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