Php – After subclassing, how can I override the parent’s constructor while still using it

oopPHP

Example: I have a class called ParentClass. ParentClass has a constructor like this:

function __construct($tpl) {
    // do something with the $tpl
}

When creating a new instance of ParentClass, I must provide that $tpl parameter like this:

$p = new ParentClass('index');

Then there's a ChildClass extends ParentClass. I want that the constructor of ChildClass provides that $tpl to ParentClass, but of course I don't want just an instance of ParentClass, but of ChildClass.

So when creating a new ChildClass instance, I want it to look like:

$foo = new ChildClass();

But internally, I want it to provide that 'index' to the constructor of ParentClass.

How can I achieve that in PHP?

Best Answer

class ChildClass extends ParentClass {
    public function __construct() {
        parent::__construct('index');
    }
}