I don't understand why print // Bar::testPrivate and // Foo::testPublic .... Does "$this" have priority? I understand Foo::testPublic but Bar::testPrivate don't enter image description here
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(); // Bar::testPrivate
// Foo::testPublic
?>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Thanks a lot guys, as a summary and joining both answers (because one complements the other) , method overwriting has its "unexpected" behavior when dealing with private methods. For protected and public methods it works reasonably as expected. I didn't know that member visibility was also given from parent to child class, so I assumed that if I understood the visibility.
CodePudding user response:
Even though Foo
extends Bar
and $myFoo
is an instance of Foo
and $this
refers to $myFoo
here; test()
is part of Bar
and testPrivate()
is private
in Foo
and so not accessible from Bar
. Since it's not accessible it executes the one locally in Bar
.
See PHP: Visibility
CodePudding user response:
There is a comment in the page where you took the example answering your question.
The manual says that "Private limits visibility only to the class that defines the item". That means extended children classes do not see the private methods of parent class and vice versa also.
As a result, parents and children can have different implementations of the "same" private methods, depending on where you call them (e.g. parent or child class instance). Why? Because private methods are visible only for the class that defines them and the child class does not see the parent's private methods. If the child doesn't see the parent's private methods, the child can't override them. Scopes are different. In other words -- each class has a private set of private variables that no-one else has access to.