parent::parent in PHP

Alexandre picture Alexandre · Nov 21, 2011 · Viewed 38k times · Source

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...)

Answer

PiTheNumber picture PiTheNumber · Nov 21, 2011

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.