【问题标题】:What's more correct parent::method() or $this->method() in a child class PHP在子类 PHP 中更正确的 parent::method() 或 $this->method()
【发布时间】:2012-11-29 05:44:37
【问题描述】:

调用父类函数更正确的方法是什么? parent::$this->

class base{

    public function get_x(){
        return 'x'; 
    }
}

class child extends base{

    public function __construct(){
        //this?
        $x = parent::get_x();
        //or this?
        $x = $this->get_x();
    } 

}

谢谢!

【问题讨论】:

    标签: php class extend


    【解决方案1】:

    没有“更正确”的合成器,因为它们有自己的意义。

    $this-> 表示“当前对象”,因此如果一个方法被覆盖,这就是您要调用的方法。

    parent:: 表示“父母的行为”。当您覆盖一个方法并且您想为父级的行为添加一些东西时,它很有用。

    所以,如果在你的类 child 的某个地方你重写了 get_x 方法并且你只想要父级的行为,使用 parent:: 如果没有,使用 $this。

    我会通过说通常建议不要在构造函数中调用 非最终方法来结束这个答案,因为任何人都可以通过扩展它来重新定义行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多