从父类访问受保护的方法

时间:2013-04-13 21:24:14

标签: php oop class

我理解当我希望它只能扩展当前类以及当前类的所有类时,我应该使方法“受保护”。

好的,grandChildClass :: method2()应该受到保护,因为孙子从子节点扩展。

但是如果从父类(例如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();}
}

1 个答案:

答案 0 :(得分:2)

如果您尝试

$p = new parentClass;
$p->method1();

对于未定义的方法,您会收到致命错误。

  

致命错误:在...中调用未定义的方法parentClass::method2() ...

但是,这样可以正常工作:

$c = new childClass;
$c->method1();

$g = new grandChildClass;
$g->method1();
$g->method3();

所有这些都会调用method2上定义的childClass