调用重写的父方法 [英] Calling an overridden parent method

查看:69
本文介绍了调用重写的父方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例代码中,父类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

这篇关于调用重写的父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆