Problem: we have an hierarchy of 3 classes, each extending the one in front (grandfather, father, son). A method – let’s say foo() – is defined in the grandfather class and overridden with a new functionality in the father class.
Question: Is there a way in the son class to access the original method (with the grandfather code) in the son class?
Of course, the obvious solution is to try something like:
parent::parent::method();
But it won’t work. It will just yield an error like:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in …
After some struggling, I have found a way to get around and access a method from the grandparent class that was overridden in the parent and run its “original” code. It’s loosely based on the strange PHP scoping that I wrote about in this article. The approach goes something like this:
class Grandfather
{
protected $_message = 'Luke, I am your grandfather';
public function say()
{
echo $this->_message;
}
}
class Father extends Grandfather
{
protected $_message = 'Luke, I am your father';
public function say()
{
throw new Exception("I can't breath under this f**cking mask
");
}
}
class Son extends Father
{
protected $_message = 'I have a very bad feeling about this';
public function say()
{
Grandfather::say();
}
}
$son = new Son();
$son->say();
Now PHP will bind the $this pointer in the body of the say() method – using the code defined in the grandfather. I guess that weird scoping is there for a reason.
The response is: “I have a very bad feeling about this”
PHP version: 5.2.9-2
PS: Nice solution!
Turn on strict notices under 5.3…
If you have a better solution, please share it…It works in PHP 5.2.x & 5.3.x without strict notices…
I would say that if you need to call a method in the Grandfather class from the Son class, then it shouldn’t be overriden by Father or Son should not inherit from Father. What you are doing here is like an inheritance from Father and Grandfather, which is a bit incestuous
Well, it does produce a warning, static methods should always be declared as static, maybe that’s why…
Not sure why it uses the strange $this scope, it should just E_ERROR or something.
I agree with Siderite. If you extends Father you are working with Fathers’ escenario. So you as Son shouldn’t be able to access an overriden method of the Grandfather.
Turn on strict notices under 5.3…