PHP:通过parent::method()从子类调用方法与$this->;调用方法的区别;方法()
假设我有一个家长班PHP:通过parent::method()从子类调用方法与$this->;调用方法的区别;方法(),php,Php,假设我有一个家长班 class parentClass { public function myMethod() { echo "parent - myMethod was called."; } } 还有下面的儿童班 class childClass extends parentClass { public function callThroughColons() { parent::myMethod(); } publ
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,我也没有收到任何警告。为什么呢
谢谢。自我:、
家长:
和静态:
都是特例。它们总是像执行非静态调用一样,也支持静态方法调用,而不抛出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 $prop = "n"; }
class y extends x { public function f() { echo parent::prop; } } // or something similar
$o = new y;
$o->f();
您仍然必须使用
$this
显式地处理属性,在这种情况下,它没有任何区别。如果父类和子类都实现了myMethod
,则会产生不同。在这种情况下,$this->myMethod()
调用当前类的实现,而parent::myMethod()
显式调用该方法的父实现parent::
是这种特殊类型调用的特殊语法,它与静态调用无关。这可以说是丑陋和/或令人困惑的
请参阅。即使我使用parentClass::myMethod()而不是parent::,我也没有收到任何警告,但我得到了总体想法-使用::运算符从继承类调用方法实际上不会生成静态调用,这是一种特殊情况。谢谢。@user2339681您收到一个E_STRICT错误。当您将错误报告的级别提高时,您将看到它。
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();