phpsubclasskeywordsubclassingmagic-constants

Referring to a PHP superclass name via a magic constant / keyword or similar construct (avoiding naming the superclass in the derived class)


The comments in the following code show what I am trying to accomplish, which is something very simple: I want to be able to refer to the name of the parent class using a PHP built-in constant (or other construct) such as __CLASS__, but which refers to the parent class rather than the current class (e.g. parent::__CLASS__) (also, while the code does not show it, if I have a subsubclass, then within such class I want to be able to refer t the parent class via something like parent::parent::__CLASS__ if at all possible).

class ParentClass {

  protected $foo;

  function __construct() {

    $this->foo = "hello";

  }

}

class DerivedClass extends ParentClass {

  public $bar;

  public $baz;

  function __construct($bar) {

    // I want to be able to write
    // something like parent:__CLASS__
    // here in place of 'ParentClass'
    // so that no matter what I rename
    // the parent class, this line will
    // always work. Is this possible?

//      if (is_a($bar, parent::__CLASS__)) {

    if (is_a($bar, 'ParentClass')) {

      $this->bar = $bar;

    } else {

      die("Unexpected.");

    }

    $this->baz = "world";

  }

  public function greet() {

    return $this->bar->foo . " " . $this->baz;

  }

}

$d = new DerivedClass(new ParentClass());
echo $d->greet();

OUTPUT:

hello world

Solution

  • You need get_parent_class Function to do it.

    function __construct($bar) {
    
        $parent = get_parent_class($this);
    
    
        if (is_a($bar, $parent)) {
    
          $this->bar = $bar;
    
        } else {
    
          die("Unexpected.");
    
        }
    
        $this->baz = "world";
    
      }
    

    if you need further level down you can use:

    class subDerivedClass extents DerivedClass{
        $superParent = get_parent_class(get_parent_class($this));
    }