【问题标题】:PHP: differences in calling a method from a child class through parent::method() vs $this->method()PHP:通过 parent::method() 与 $this->method() 从子类调用方法的区别
【发布时间】:2013-06-04 19:04:31
【问题描述】:

假设我有一个父类

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

和下面的子类

class childClass extends parentClass {
    public function callThroughColons() {
        parent::myMethod();
    }
    public function callThroughArrow() {
        $this->myMethod();
    }
}

$myVar = new childClass();
$myVar->callThroughColons();
$myVar->callThroughArrow();

在继承类中使用两种不同的方式调用 myMethod() 有什么区别? 我能想到的唯一区别是 childClass 是否用他自己的版本覆盖了 myMethod(),但是还有其他显着的区别吗?

我认为双冒号运算符 (::) 应该只用于调用静态方法,但在调用 $myVar->callThroughColons() 时我没有收到任何警告,即使启用了 E_STRICT 和 E_ALL。这是为什么呢?

谢谢。

【问题讨论】:

    标签: php


    【解决方案1】:

    在这种情况下,它没有区别。如果父类和子类都实现myMethod,它确实会有所不同。在这种情况下,$this->myMethod() 调用当前类的实现,而parent::myMethod() 显式调用父类的方法实现。 parent:: 是这种特殊调用的特殊语法,它与静态调用无关。这可以说是丑陋和/或令人困惑的。

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

    【讨论】:

      【解决方案2】:

      self::parent::static:: 是特殊情况。它们总是表现得好像您会进行非静态调用,并且还支持静态方法调用而不抛出 E_STRICT

      只有在使用类名而不是那些相对标识符时才会遇到问题。

      那么可行的是:

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

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

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

      但行不通的是:

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

      您仍然需要使用$this 明确地处理属性。

      【讨论】:

      • 即使我使用 parentClass::myMethod() 而不是 parent::,我也没有收到任何警告,但我明白了整体的想法 - 使用 :: 运算符从继承类调用方法并不是真的生成一个静态调用,这是一个特例。谢谢。
      • @user2339681 您收到 E_STRICT 错误。当您将错误报告调高时,您会看到它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 1970-01-01
      相关资源
      最近更新 更多