PHP How to extend a class without override

php, web

Solution

Use this:

class a {
  public function __construct(){
    echo "hello";
  }
}

class b extends a {
  public function __construct(){
   parent::__construct(); // this line calls the parent (a) constructor
   echo "world";
    }
}

The PHP Constructors and Destructors doc states:

Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).

Problem

For example if I had this code: ``` class a { function __construct() { echo "hello"; } class b extends a{ function __construct() { echo "world"; } } ``` I want it to output "Hello World". Instead class A constructer is overrided by class B constrcter so will output "world" only.

Original source