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

前端 未结 2 1141
渐次进展
渐次进展 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:43

    self::, parent:: and static:: are special cases. They always act as if you'd do a non-static call and support also static method calls without throwing an E_STRICT.

    You will only have problems when you use the class' names instead of those relative identifiers.

    So what will work is:

    class x { public function n() { echo "n"; } }
    class y extends x { public function f() { parent::n(); } }
    $o = new y;
    $o->f();
    

    and

    class x { public static function n() { echo "n"; } }
    class y extends x { public function f() { parent::n(); } }
    $o = new y;
    $o->f();
    

    and

    class x { public static $prop = "n"; }
    class y extends x { public function f() { echo parent::$prop; } }
    $o = new y;
    $o->f();
    

    But what won't work is:

    class x { public $prop = "n"; }
    class y extends x { public function f() { echo parent::prop; } } // or something similar
    $o = new y;
    $o->f();
    

    You still have to address properties explicitly with $this.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题