Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: differences in calling a method from a child class through parent::method() vs $this->method()

Tags:

php

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.

like image 943
user2339681 Avatar asked Jun 04 '13 19:06

user2339681


1 Answers

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.

like image 59
deceze Avatar answered Oct 19 '22 01:10

deceze