tags:

views:

105

answers:

4

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?

+2  A: 
class ChildClass extends ParentClass {
    public function __construct() {
        parent::__construct('index');
    }
}
Ivan Krechetov
+1  A: 

With parent::__construct() you can call the constructor of the parent.

class ChildClass extends ParentClass
{
    function __construct()
    {
        parent::__construct('index');
    }
}
Ikke
+1  A: 

Try this:

class ChildClass extends ParentClass{
  function __construct($tpl) {
    parent::__construct($tpl);
  }
}

Now create the instance of childclass:

$p = new ChildClass('index');

Note: In your child class, you should include the parent class.

Sarfraz
Thanks! What I want to achieve is that I don't have to provide 'index' anymore with using ChildClass. That's the whole point of ChildClass :-)
openfrog
+1  A: 

You can call parent::_construct('index'); from within the ChildClass constructor. This will construct the base class using index.

Rich Adams