[英]Accessing a protected method from a parent class
我知道當我希望它只能擴展當前類以及當前類的所有類時,我應該使方法“受保護”。
好的,grandChildClass :: method2()應該受到保護,因為孫子是從child擴展的。
但是如果從父類(如parentClass :: method2())訪問它應該是什么?
class parentClass
{
public function method1() {$this->method2();}
}
class childClass extends parentClass
{
protected function method2() {}
}
class grandChildClass extends childClass
{
public function method3() {$this->method2();}
}
如果你試着
$p = new parentClass;
$p->method1();
對於未定義的方法,您會收到致命錯誤。
致命錯誤:在......上調用未定義的方法
parentClass::method2()
...
但是,這樣可以正常工作:
$c = new childClass;
$c->method1();
$g = new grandChildClass;
$g->method1();
$g->method3();
所有這些都將調用childClass
定義的method2
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.