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 use a separate internal method (e.g. _doStuff to complement doStuff) and call that directly from the grandchild, through the parent.
// Base class that everything inherits
class Grandpa {
protected function _doStuff() {
// grandpa's logic
echo 'grandpa ';
}
public function doStuff() {
$this->_doStuff();
}
}
class Papa extends Grandpa {
public function doStuff() {
parent::doStuff();
echo 'papa ';
}
}
class Kiddo extends Papa {
public function doStuff() {
// Calls _doStuff instead of doStuff
parent::_doStuff();
echo 'kiddo';
}
}
$person = new Grandpa();
$person->doStuff();
echo "\n";
$person = new Papa();
$person->doStuff();
echo "\n";
$person = new Kiddo();
$person->doStuff();
shows
grandpa
grandpa papa
grandpa kiddo