Reputation: 11
I was wondering how I should interpret the following code (source: http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php)
<?php
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()\n";
}
}
class OtherClass extends MyClass
{
// Override parent's definition
public function myFunc()
{
// But still call the parent function
parent::myFunc();
echo "OtherClass::myFunc()\n";
}
}
$class = new OtherClass();
$class->myFunc();
?>
My question is: why is the scope resolution operator ('::') used to access the parent function:
parent::myFunc();
To me, the double colon suggests a static member / method. When creating the OtherClass object:
$class = new OtherClass();
there will be a new instance (object) of the OtherClass. But will there be an instance of the parent class at the same time? How should I interpretet this?
I understand the idea of creating a new object from the extended OtherClass, but how should I interpret its parent class: like a static class or like an object (copy of class)?
I hope my question makes sense.
Upvotes: 1
Views: 386
Reputation: 1194
parent::myFunc();
is not a static invocation, it is a bit confusing that it used the same operator though. You only need this operator if you have overridden the method and want to call the parent method.
there will be a new instance (object) of the OtherClass. But will there be an instance of the parent class at the same time? How should I interpretet this?
Because OtherClass
extends MyClass
the single object you constructed is an instance of both these classes at the same time.
Upvotes: 0
Reputation: 72346
An object of class OtherClass
is also an object of class MyClass
because class OtherClass
extends class MyClass
. It has all the properties and methods of MyClass
but some of the methods might be redefined in OtherClass
.
The scope resolution operator is used both to access static class members and methods (using class name, self
or static
) but also to access methods defined in the parent class (using parent
).
Upvotes: 1