开发者

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 testFunct开发者_JAVA技巧ion()
    {
        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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜