Reputation: 16142
class Bar{
public function test(){
$this->testPublic();
$this->testPrivate();
}
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();
//Foo::testPublic
//Bar::testPrivate
I'm having a lot of trouble understanding this output. Would someone be able to give me a clear succinct explanation of what is going on? I'm learning OOP and wanted to know how to use extensions to override the parent class functions.
Upvotes: 3
Views: 46
Reputation: 54771
The $this references the current object. So when you do the following.
$this->testPublic();
It will call testPublic() for the top most class that implements that function.
If you want to only call the parent class, then there is the parent keyword.
parent::testPublic();
That will call testPublic() on the class below the current object.
Becare full not to confuse the -> operator with the :: operator.
The :: operator references the class definition of an object, where as -> references the instance of an object.
self::testPublic();
$foo::testPublic();
That references a static function called testPublic(), and static methods are defined at the class level.
$foo->testPublic();
$this->testPublic();
That references a function as part of the instance of an object, and there is a vtable used to look up which object instance level should be called.
Upvotes: 0
Reputation: 254926
The test()
method calls 2 methods:
testPublic
- it's a public one, so it was overriden in the Foo
. So the Foo::testPublic
is calledtestPrivate
- it's a private one, so it's only visible for each class itself. For the caller method (it's Bar
) - it's a Bar::testPrivate
So - if the method is public
or protected
- it can be overriden and called from the ancestor/child; if it's private
- it cannot.
Upvotes: 5