簡體   English   中英

從父類訪問受保護的方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM