Executing __constructor () in php inheritance

In php, if A extends B, does B _constrctor () execute automatically when A is instantiated? or do I need to call parent β†’ _ constructor ()?

+3
source share
4 answers

PHP is looking for the topmost (closest to the class instance) method __constructthat it can find. Then he performs only one.

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 it parentturns to the next list up until it is no longer there (at what point it will generate an error) ...

So, in the class Estart parent::__construct()will execute the class constructor B.

In the class Bstart parent::__construct()will execute the class constructor A.

A parent::__construct() , ...

+8

: .

:

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

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

$ab = new B();

, .

+1

You need to call "parent :: __ construct ()" from constructor A if A has one. Otherwise, you do not need.

0
source
class A {
    function __construct() {
        echo 5;
    }
}
class B_no_Constructor extends A {

}
class B_with_Constructor extends A {
    function __construct(){}
}
//try one
//new B_no_Constructor; //outputs 5
//new B_with_Constructor; //outputs nothing
0
source

Source: https://habr.com/ru/post/1784172/


All Articles