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