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!
PHP has three visibility keywords - public, private and protected. A class member declared with public keyword is accessible from anywhare. A protected member is accessible from within its class and by inheriting class.
Members declared protected can be accessed only within the class itself and by inherited and parent classes.
PHP - What is Inheritance? Inheritance in OOP = When a class derives from another class. The child class will inherit all the public and protected properties and methods from the parent class. In addition, it can have its own properties and methods. An inherited class is defined by using the extends keyword.
Visibility is declared using a visibility keyword to declare what level of visibility a property or method has. The three levels define whether a property or method can be accessed outside of the class, and in classes that extend the class.
Probably becuase testPrivate
is, 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 private
So, what exactly happens is the following: The child class will not redeclare the method testPrivate
but instead creates it's own version in the "scope" if the child object only. As test()
is defined in the parent class, it will access the parents testPrivate
.
If you would redeclare the test
function in the child class, it should access the childs? testPrivate()
method.
Private methods are not visible to anything but the declaring class. Since you call testPrivate
from the parent class, the only method it has access to is its own declaration of the method. Thus you get the output you see. Had the access modifier been protected
, however, then you would get the output you expect, since protected methods are visible throughout the inheritance chain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With