Php 从父类访问受保护的方法

Php 从父类访问受保护的方法,php,oop,class,Php,Oop,Class,我理解,当我希望一个方法只对扩展当前类以及当前类的所有类可用时,我应该将其设置为“受保护” 好的,应该保护孙子类::method2(),因为孙子是从child扩展而来的 但是,如果从父类(如parentClass::method2())访问,它应该是什么呢 如果你想 $p = new parentClass; $p->method1(); 对于未定义的方法,您将得到一个致命错误 致命错误:在。。。在线 但是,这将很好地工作: $c = new childClass; $c->met

我理解,当我希望一个方法只对扩展当前类以及当前类的所有类可用时,我应该将其设置为“受保护”

好的,应该保护孙子类::method2(),因为孙子是从child扩展而来的

但是,如果从父类(如parentClass::method2())访问,它应该是什么呢

如果你想

$p = new parentClass;
$p->method1();
对于未定义的方法,您将得到一个致命错误

致命错误:在。。。在线

但是,这将很好地工作:

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

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

所有这些都将调用
method2
,如
childClass

上所定义,以使其更干净
parentClass
可以定义
method2
的纯虚拟版本,如下所示
virtualmethod2()=0。这将明确要求任何子类实现
method2()
函数,以便可以调用
parentClass
的我的方法。谢谢,我希望它能像您所说的那样工作!我把自己弄糊涂了,当时正在访问父类中定义的方法,但是是从孙类中访问的,所以显然childClass方法工作得很好。@Alan:PHP中没有
virtual
方法。您可以将类及其方法定义为
abstract
(这意味着它们只有定义,不能实例化)。谢谢@MadaraUchiha,这就是我的意思,将其定义为abstract。我把C++和PHP混合起来了。
$c = new childClass;
$c->method1();

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