Search code examples
phpsubclassstatic-methodssuperclassbase-class

How to refer to parent class of base class from sub-sub-base-class static method without specifying base class name


In PHP, I want to call a static method in the parent of the parent class from the sub-sub-class, without referring to the parent class of the parent class's name (please see the comment in the code below):

class Base {

  public static function helloStatic() {

    return "Hello base!\n";

  }

}

class Foo extends Base {

  private $fooMember;

  public static function helloStatic() {

    return "Hello foo!\n";

  }

  private function __construct() {

    $this->fooMember = "hello";

  }

  public function getFooMember() {

    return $this->fooMember;

  }

}

class Bar extends Foo {

  private $barMember;

  public static function helloStatic() {

    // I want to write the equivalent of:
    //echo Base::helloStatic();
    // here *without specifying any class names*

    echo get_parent_class(get_parent_class())::helloStatic();

  }

}

echo Bar::helloStatic();

EXPECTED OUTPUT:

Hello base!

OUTPUT:

<br />
<b>Parse error</b>:  syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ';' on line <b>45</b><br />

Solution

  • Store the parent class name inside a variable and use that variable to call the static method. Like this:

    $parentClassName = get_parent_class(get_parent_class());
    echo $parentClassName::helloStatic();