PHP: differences in calling a method from a child class through parent::method() vs $this->method()

前端 未结 2 1166
渐次进展
渐次进展 2021-01-12 08:14

Say I have a parent class

class parentClass {
    public function myMethod() {
        echo \"parent - myMethod was called.\";
    }
}

and

2条回答
  •  孤独总比滥情好
    2021-01-12 08:48

    In this case it makes no difference. It does make a difference if both the parent and child class implement myMethod. In this case, $this->myMethod() calls the implementation of the current class, while parent::myMethod() explicitly calls the parent's implementation of the method. parent:: is a special syntax for this special kind of call, it has nothing to do with static calls. It's arguably ugly and/or confusing.

    See https://stackoverflow.com/a/13875728/476.

提交回复
热议问题