3

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()?

4 Answers 4

8

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...

Sign up to request clarification or add additional context in comments.

Comments

1

The answer is you have to call it.

A simple test:

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

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

$ab = new B();

Should tell you all you need to know.

Comments

0

You need to call "parent::__construct()" from A's constructor, if A has one. Otherwise you don't need to.

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.