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

Say I have a parent class

class parentClass { public function myMethod() { echo "parent - myMethod was called."; } } 

and the next 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 two different ways to call myMethod () from an inheritance class? The only difference I can think of is if childClass overrides myMethod () with its own version, but are there any other significant differences?

I thought the double colons (:) operator should only be used to call static methods, but I don't get a warning when calling $ myVar-> callThroughColons () even with E_STRICT and E_ALL. Why is this?

Thanks.

+7
source share
2 answers

self:: , parent:: and static:: are special cases. They always act as if you made a non-static call and also supported calls to static methods without throwing E_STRICT .

You will only have problems using class names instead of these relative identifiers.

So what will work:

 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 does not work:

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

You should still explicitly access properties using $this .

+3
source

In this case, it does not matter. It matters if both the parent and child classes implement myMethod . In this case, $this->myMethod() calls the implementation of the current class, and parent::myMethod() explicitly calls the parent implementation of the method. parent:: is a special syntax for this particular type of call; it has nothing to do with static calls. This is possibly ugly and / or confusing.

See https://stackoverflow.com/a/414829/

+5
source

All Articles