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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With