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

前端 未结 2 1167
渐次进展
渐次进展 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.

提交回复
热议问题