A
A
Alexey Dabalaev2016-07-07 21:41:30
PHP
Alexey Dabalaev, 2016-07-07 21:41:30

How to access the constructor of the (first) parent class?

Hello.
During the discussion (well, you know, at such moments all sorts of thoughts come to mind, which is very good), the question arose - is it possible to call the constructor of the "first" parent class with such an inheritance hierarchy:

class Prnt {
  public function __construct() {
    echo 'In Prnt';
  }
}

class A extends Prnt {
  public function __construct() {
    echo 'In A';
  }
}

class B extends A {
  public function __construct() {
    echo 'In B';
  }
}

How to call the constructor of the parent class A in the constructor of class B - it doesn’t raise questions, but here’s how to call the constructor of class Prnt from the constructor of class B (at the same time, in the constructor of class A there is no call to the constructor of class Prnt) - here we settled on the fact that it is impossible implement such a challenge.
It seems that the question is closed, but still I would like to hear the opinion of more experienced people.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Cat Anton, 2016-07-07
@AleksDab

class B extends A
{
    public function __construct()
    {
        echo 'In B';
        Prnt::__construct();
    }
}

https://ideone.com/4dWP79
class B extends A
{
    public function __construct() 
    {
        echo 'In B';
 
        $reflection = new ReflectionClass(self::class);
        $parent = $reflection->getParentClass();
        while ($parent->getParentClass()) {
            $parent = $parent->getParentClass();
        }
        $class = $parent->getName();
        $class::__construct();
    }
}

https://ideone.com/XUuYme
Similarly, you can refer to any method (not just a constructor) of any ancestor class, if the scope allows.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question