Having the following class hierarchy:
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
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()
?
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.
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?