Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a subclass inherit also the constructor of the parent class, or must every class have its own constructor?

Tags:

oop

php

Lets say I have an abstract ParentClass and a ChildClass. ChildClass extends ParentClass. Now ParentClass has got this nice constructor:

function __construct($tplFile) {
    $this->$tplFile = $tplFile;
}

Will ChildClass automatically inherit this one? And if I don't add any constructor to ChildClass, will I be able to say $foo = new ChildClass("foo.tpl.php"); so that the constructor of ParentClass gets called?

like image 801
openfrog Avatar asked Dec 25 '09 22:12

openfrog


2 Answers

From the PHP manual:

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.

like image 151
Don Avatar answered Oct 31 '22 20:10

Don


ChildClass will automatically inherit the constructor.

like image 27
Pekka Avatar answered Oct 31 '22 20:10

Pekka