20

In the PHP Constructors and Destructors documentation it 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.

But what if the child class does not call a constructor, will the parent constructor still be called? Or should we create a constructor that calls the parent constructor anyway?

IE:

class BaseClass {
   function __construct() {
       print "In BaseClass constructor\n";
   }
}

class SubClass extends BaseClass {
   function __construct() {
       parent::__construct();
   }
}
Kirill Fuchs
  • 13,446
  • 4
  • 42
  • 72

2 Answers2

19

Maybe this was sort of obvious but did some looking around, and a direct answer to this question surprisingly wasn't very easy to find so here it is:

If the child class does NOT define a constructor then the parent constructor will be called.

In the example below $obj will still call the constructor from BaseClass because SubClass never called a constructor.

class BaseClass {
    function __construct() {
       print "In BaseClass constructor\n";
    }
}

class SubClass extends BaseClass {
    //I do not have a constructor :(
}

$obj = new SubClass();
Kirill Fuchs
  • 13,446
  • 4
  • 42
  • 72
  • 2
    Maybe [the manual](http://www.php.net/manual/en/language.oop5.decon.php) has been updated more recently, but it does state, "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)." – MrWhite Feb 06 '13 at 15:05
  • Can you even declare a constructor as private? That seems to defeat the purpose of having a class in the first place. – eggmatters Feb 18 '16 at 20:41
  • @eggmatters: Check this answer on private constructors: http://stackoverflow.com/a/2816139/1488445 – Juha Untinen May 27 '16 at 08:47
6

Take into account a constructor is a method that can be overridden as any other method. If the parent class has a constructor, all its children classes will inherit that constructor. If a child overrides the constructor, this will be used when creating new objects and parent's constructor is not called implicitly. If the child does not override the constructor, the parent's constructor will be used. This concept applies to multiple inheritance.

Al_
  • 1,481
  • 1
  • 11
  • 22