由于您在子级中覆盖$name
,因此该属性将具有子级的属性值。然后您无法访问父值。任何其他方式都没有任何意义,因为该属性是公共的,这意味着该属性对子(和外部)可见,并且对其进行修改将改变基本值。因此,对于该实例,它实际上是一个相同的属性和值。
拥有两个不同的同名属性的唯一方法是将基本属性声明为私有,将子属性声明为非私有,然后调用可以访问基本属性的方法,例如
class Foo
{
private $name = 'foo';
public function show()
{
echo $this->name;
}
}
class Bar extends Foo
{
public $name = 'bar';
public function show()
{
parent::show();
echo $this->name;
}
}
(new Bar)->show(); // prints foobar
由于您的 C++ 示例调用使用范围解析运算符::
,您可能正在寻找类/静态属性:
class Foo
{
static public $name = 'foo';
public function show()
{
echo static::$name; // late static binding
echo self::$name; // static binding
}
}
class Bar extends Foo
{
static public $name = 'bar';
public function show()
{
parent::show(); // calling parent's show()
echo parent::$name; // calling parent's $foo
}
}
(new Bar)->show(); // prints barfoofoo