Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

executing __constructor() in php inheritance

Tags:

oop

php

In php, if A extends B, does B's _constrctor() get executed automatically when A is instantiated? or do I have to call parent->_constructor()?

like image 744
Desmond Liang Avatar asked Dec 01 '25 08:12

Desmond Liang


1 Answers

PHP looks for the top-most (closest to the instantiated class) __construct method it can find. It then executes that one only.

Class A {
    public function __construct() {
        echo "From A";
    }
}
Class B extends A {
    public function __construct() {
        echo "From B";
    }
}
Class C extends A {}
Class D extends B {}
Class E extends B {
    public function __construct() {
        echo "from E";
    }
}

new A(); // From A
new B(); // From B
new C(); // From A
new D(); // From B
new E(); // From E

And parent accesses the next one up the list until there are no more (at which point it'll generate an error)...

So, in class E, running parent::__construct() would execute class B's constructor.

In class B, running parent::__construct() would execute class A's constructor.

In class A, running parent::__construct() will generate an error since there is no constructor...

like image 53
ircmaxell Avatar answered Dec 03 '25 21:12

ircmaxell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!