问题描述
具有以下类层次结构:
class TheParent{
public function parse(){
$this->validate();
}
}
class TheChild extends TheParent{
private function validate(){
echo 'Valid!!';
}
}
$child= new TheChild();
$child->parse();
这个步骤的顺序是什么?
What is the sequence of steps in which this is going to work?
问题是当我运行该代码时出现以下错误:
The problem is when I ran that code it gave the following error:
Fatal error: Call to private method TheChild::validate() from context 'TheParent' on line 4
由于 TheChild
继承自 TheParent
不应该 $ this
在中调用parse()
指的是 $ child
的实例,所以验证()
将显示 parse()
?
Since TheChild
inherits from TheParent
shouldn't $this
called in parse()
be referring to the instance of $child
, so validate()
will be visible to parse()
?
注意:
在做了一些研究之后,我发现这个问题的解决方案要么是 validate()
函数受保护的
根据此评论在PHP手册中,虽然我不完全理解为什么它在这种情况下工作。
Note:
After doing some research I found that the solution to this problem would either make the validate()
function protected
according to this comment in the PHP manual, although I don't fully understand why it is working in this case.
第二种解决方案是创建抽象保护
方法 validate()
在父级中并将其覆盖在子级(这将是多余的)第一个解决方案中,因为 protected
可以从父级访问子级的方法?! !
The second solution is to create an abstract protected
method validate()
in the parent and override it in the child (which will be redundant) to the first solution as protected
methods of a child can be accessed from the parent?!!
在这种情况下,有人可以解释一下继承是如何工作的吗?
Can someone please explain how the inheritance works in this case?
推荐答案
你对遗产的看法是正确的,而不是可见性。
Your idea of inheritence is correct, just not the visibility.
受保护的类可以使用,并且继承和父类,private只能在它定义的实际类中使用。
Protected can be used by the class and inherited and parent classes, private can only be used in the actual class it was defined.
这篇关于在PHP中从父类调用子方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!