Please help me. Why the output is like such? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

19th Oct 2021, 10:05 AM
Santosh Pattnaik
Santosh Pattnaik - avatar
1 Answer
+ 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
20th Oct 2021, 1:50 PM
Santosh Pattnaik
Santosh Pattnaik - avatar