Sometimes I need to execute grandparent method (that is, bypass the parent method), I know this is code smell, but sometimes I can\'t change the other classes (frameworks, l
You can call the grandparent directly by name (does not need Reflection, nor call_user_func
).
class Base {
protected function getFoo() {
return 'Base';
}
}
class Child extends Base {
protected function getFoo() {
return parent::getFoo() . ' Child';
}
}
class Grandchild extends Child {
protected function getFoo() {
return Base::getFoo() . ' Grandchild';
}
}
The Base::getFoo
call may look like a static call (due to the colon ::
syntax), however it is not. Just like parent::
isn't static, either.
Calling a method from the inheritance chain within a class will correctly bind the $this
value, invoke it as a regular method, honour the visibility rules (e.g. protected), and is not a violation of any kind!
This may look a bit strange at first, but, this is the way to do it in PHP.