inheritance - PHP Calling a method in instantiated class from parent class
I have a parent class with below code:
class ParentClass {
public function parentMethod()
{
if (childMethodExist()) {
$this->childMethod();
}
}
}
class ChildClass extends ParentClass {
public function childMethod()
// statement 1
// statement 2
}
}
Now I want to call parentMethod()
which will intern call childMethod()
. My problem is am I doing this correct (I already get eslint errors for $this->childMethod();
in VSCode). But the code works as I expect.
Answer
Solution:
What is childMethodExist
? That should be method_exists($this, 'childMethod')
, I'd say?
But a better way in general would be to overload the parentMethod
in the child, something like:
class ChildClass extends ParentClass {
public function parentMethod() {
// some child specific code might go here
parent::parentMethod();
// and some child specific code might go here
}
}
Then, you just always call $object->parentMethod()
from wherever you have something that's either a parent or a child, and it'll work. This way, your parent object doesn't know anything at all about the child object (which it shouldn't!), but its implementation is still used, so you prevent code duplication.