调用重写的父方法
在下面的示例代码中,父类Foo中的方法test()被子类Bar中的方法test()覆盖。是否可以从Bar::test()调用Foo::test()?
class Foo
{
$text = "world
";
protected function test() {
echo $this->text;
}
}// class Foo
class Bar extends Foo
{
public function test() {
echo "Hello, ";
// Cannot use 'parent::test()' because, in this case,
// Foo::test() requires object data from $this
parent::test();
}
}// class Bar extends Foo
$x = new Bar;
$x->test();
解决方案
在方法名称前使用parent::,例如
parent::test();
参见parent
相关文章