Say I have a parent class
class parentClass {
public function myMethod() {
echo "parent - myMethod was called.";
}
}
and the following child class
class childClass extends parentClass {
public function callThroughColons() {
parent::myMethod();
}
public function callThroughArrow() {
$this->myMethod();
}
}
$myVar = new childClass();
$myVar->callThroughColons();
$myVar->callThroughArrow();
what is the difference in using the two different ways to call myMethod() from within an inheriting class? The only difference I can think of is if childClass overrides myMethod() with his own version, but are there any other significant differences?
I thought the double colons operator (::) was supposed to be used to call static methods only, but I don't get any warning when calling $myVar->callThroughColons(), even with E_STRICT and E_ALL on. Why is that?
Thank you.
In this case it makes no difference. It does make a difference if both the parent and child class implement myMethod
. In this case, $this->myMethod()
calls the implementation of the current class, while parent::myMethod()
explicitly calls the parent's implementation of the method. parent::
is a special syntax for this special kind of call, it has nothing to do with static calls. It's arguably ugly and/or confusing.
See https://stackoverflow.com/a/13875728/476.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With