Aesphere
Aesphere

Reputation: 604

using $this or parent:: to call inherited methods?

Not really a problem, more like curiosity on my part but as an example, say I have a php class:

class baseTestMain
{
    protected function testFunction()
    {
        echo 'baseTestMain says hi';
    }
}

and another class that extends from that class above:

class aSubClass extends baseTestMain
{
    public function doingSomething()
    {
        parent::testFunction();
        //someextrastuffhere
    }
}

Normally, when I want to call a parent method when defining a new method in the subclass I would do the above - parent::methodnamehere() however instead of parent:: you can also use $this->methodname() and the operation would be the same.

class aSubClass extends baseTestMain
{
    public function doingSomething()
    {
        $this->testFunction();
        //someextrastuffhere
    }
}

So what I'm asking is, should I use parent::testFunction(); or use $this->testFunction(); ? or is there a difference to it that I've missed? If not, whats your preference or the preferred method?

Do note that I am not overriding or extending that function in the subclass, essentially the implementation is carried over from the parent.

Upvotes: 19

Views: 9119

Answers (2)

BoltClock
BoltClock

Reputation: 723538

In your case, since aSubClass::testFunction() is inherited from baseTestMain::testFunction(), use $this->testFunction(). You should only use parent::testFunction() if you're going to override that method in your subclass, within its implementation.

The difference is that parent:: calls the parent's implementation while $this-> calls the child's implementation if the child has its own implementation instead of inheriting it from the parent.

Upvotes: 36

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

Calling the method on the parent prevents the class's children from participating in polymorphism properly since their redefinition of the method will never be called.

Upvotes: 7

Related Questions