I have difficulties in understanding why we get the output of this code:
<?php
class Bar
{
public function test() {
$this->testPrivate();
$this->testPublic();
}
public function testPublic() {
echo "Bar::testPublic\n";
}
private function testPrivate() {
echo "Bar::testPrivate\n";
}
}
class Foo extends Bar
{
public function testPublic() {
echo "Foo::testPublic\n";
}
private function testPrivate() {
echo "Foo::testPrivate\n";
}
}
$myFoo = new foo();
$myFoo->test();
?>
So Foo extends Bar. $myfoo is an obect of the class Foo. Foo doesn’t have a method, called test(), so it extends it from its parent Bar. But why the result of test() is
Bar::testPrivate
Foo::testPublic
Can you please explain me why the first isn’t Foo::testPrivate, when this parent’s method is overridden in the child?
Thank you very much in advance!
Probably becuase
testPrivateis, as the name already suggests, a private method and won’t be inherited / overwritten by class inheritance.On the php.net manual page you probably got that code from it explicitely states that
We can redeclare the public and protected method, but not privateSo, what exactly happens is the following: The child class will not redeclare the method
testPrivatebut instead creates it’s own version in the “scope” if the child object only. Astest()is defined in the parent class, it will access the parentstestPrivate.If you would redeclare the
testfunction in the child class, it should access the childs? testPrivate()method.