Inheritance in PHP works the same way as in most object-oriented languages.
When you have a βvirtualβ method, the method is not attached directly to the caller. Instead, each class contains a small lookup table that says "this method name is associated with this implementation." So, when you say $this->testPublic()
, what actually happens is that PHP:
- Gets a virtual table for the current class
- View virtual table table for
testPublic
in this table - Invokes a method for which search points
Since Foo
overrides testPublic
, its virtual table contains an entry for testPublic
pointing to Foo::testPublic
.
Now that private methods, the behavior is different. Since, as you read correctly, private methods cannot be overridden, calling a private method never leads to finding a virtual table. That is, private methods cannot be virtual and must always be defined in the class that uses them.
So the effect is that the name is bound during the declaration: all Foo
methods will call Foo::testPrivate
when they say $this->testPrivate
, and all Bar
methods will call Bar::testPrivate
.
To summarize, arguing that "inherited methods are copied for a child" are incorrect. In fact, it happens that a child element begins by filling its parent name class table with the names of the method names, and then adds its own functions and replaces any overridden entries. When you call $this->something
, this lookup table is requested for the current class of objects. Therefore, if $this
is an instance of Foo
, and Foo
overrides testPublic
, you get Foo::testPublic
. If $this
is an instance of Bar
, you will get Bar::testPublic
.
source share