user2339681
user2339681

Reputation: 103

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

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.

Upvotes: 7

Views: 306

Answers (2)

bwoebi
bwoebi

Reputation: 23777

self::, parent:: and static:: are special cases. They always act as if you'd do a non-static call and support also static method calls without throwing an E_STRICT.

You will only have problems when you use the class' names instead of those relative identifiers.

So what will work is:

class x { public function n() { echo "n"; } }
class y extends x { public function f() { parent::n(); } }
$o = new y;
$o->f();

and

class x { public static function n() { echo "n"; } }
class y extends x { public function f() { parent::n(); } }
$o = new y;
$o->f();

and

class x { public static $prop = "n"; }
class y extends x { public function f() { echo parent::$prop; } }
$o = new y;
$o->f();

But what won't work is:

class x { public $prop = "n"; }
class y extends x { public function f() { echo parent::prop; } } // or something similar
$o = new y;
$o->f();

You still have to address properties explicitly with $this.

Upvotes: 3

deceze
deceze

Reputation: 522024

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.

Upvotes: 5

Related Questions