I have confused from an example in php manual. It’s about visibility. Here is the example.
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();
?>
http://www.php.net/manual/en/language.oop5.visibility.php
This example outputs
Bar::testPrivate
Foo::testPublic
Please can you explain how this happen?
why both testPublic() are not called?
I put a var_dump($this) in Bar class construct. It prints object(Foo)[1]. The thing I know is private properties can be called withing same class.
Then how “Bar::testPrivate” is called?
When you call
$myFoo->test(), it runs the code in the context ofBarbecause theFooclass didn’t override it.Inside
Bar::test(), when$this->testPrivate()gets called, the interpreter will look atFoofirst but that method is private (and private methods from descendent classes can’t be called fromBar), so it goes one level up until it can find a suitable method; in this case that would beBar::testPrivate().In contrast, when
$this->testPublic()gets called, the interpreter immediately finds a suitable method inFooand runs it.Edit
Only one method gets called when you run
$this->testPublic(), the furthest one (in terms of distance to the base class).If
Foo::testPublic()needs to also execute the parent’s implementation, you should writeparent::testPublic()inside that method.