Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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.

like image 929
Aesphere Avatar asked Feb 24 '11 08:02

Aesphere


People also ask

How do you call parent class method and child class method in polymorphism?

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method. This would print: I'm the child.

How do you call a parent class in PHP?

To call the constructor of the parent class from the constructor of the child class, you use the parent::__construct(arguments) syntax. The syntax for calling the parent constructor is the same as a regular method.


1 Answers

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.

like image 124
BoltClock Avatar answered Oct 07 '22 17:10

BoltClock