parent::parent in PHP
I search a way to access to the parent, parent function of a class without to call the parent... Hmmm, that sound a bit weird explanation so i will give an example:
class myclass
{
public function test() { return 'level 1'; }
}
class myclass2 extends myclass
{
public function test() { return parent::test() . '-level 2'; }
}
class myclass3 extends myclass2
{
public function test() { return parent::test() . '-level 3'; }
}
$example = new myclass3();
echo $example->test(); // should display "level 1-level 2-level 3"
I would like to display "level 1-level 3" then doing something like that:
class myclass3 extends myclass2
{
public function test() { return parent::parent::test() . '-level 3'; }
}
Do you have an idea how I can do this? (I am not allow to edit myclass and myclass2, they are part of a framework...)
Simple solution. Use the root object myclass directly:
class myclass3 extends myclass2
{
public function test() { return myclass::test() . '-level 3'; }
}
If you need a more general approach have a look at outis answer.
You could do it using get_parent_class
function get_grandparent_class($thing) {
if (is_object($thing)) {
$thing = get_class($thing);
}
return get_parent_class(get_parent_class($thing));
}
class myclass3 extends myclass2 {
public function test() {
$grandparent = get_grandparent_class($this);
return $grandparent::test() . '-level 3';
}
}
Or you could use reflection:
function get_grandparent_class($thing) {
if (is_object($thing)) {
$thing = get_class($thing);
}
$class = new ReflectionClass($thing);
return $class->getParentClass()->getParentClass()->getName();
}
However, it may not be a good idea, depending on what you're trying to achieve.