+ 1
Please help me. Why the output is like such?
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(); The output is "Bar::testPrivate Foo::testPublic" Somebody explain the execution process.
1 Antwort
+ 2
I got know the answer from stackoverflow so I am answering this question myself. Others who also have the doubts can see this question.
As the test() function is in parent class it is calling the private function of parent class and not of the child class whose object is calling the test() method.
The private method of the parent class cannot be inherited by the child class as per syntax rules. So the private method in the child class is formed in a different scope than of parent class' private method.
Since test() method is in the parent class it calls parent class' private method so output is 'Bar::testPrivate' and since test() method is called by child class object the public method(inherited in child) is called, so the output is 'Foo::testPublic'.
https://stackoverflow.com/questions/13044281/inheritance-and-visibility-php