繁体   English   中英

什么更正确的子类PHP中的parent :: method()或$ this-> method()

[英]What's more correct parent::method() or $this->method() in a child class PHP

调用父类函数的更正确的方法是什么? 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();
    } 

}

谢谢!

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

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

parent::表示“父母的行为”。 当您覆盖方法并且想要向父级行为添加内容时,它非常有用。

因此,如果您的类child某个地方覆盖了get_x方法并且您只想要父项的行为,请使用parent :: if not,使用$ this。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM