views:

84

answers:

2

If I have a parent class that is extended by lots and lots of other classes, and I want to make sure the parent class's constructor is ALWAYS run, is it a bad idea to declare the constructor final?

I was thinking of doing something like this:

class ParentClass {

    public final function __construct() {

        //parent class initialization...

        $this->construct();

    }

    protected function init() {

        echo 'constructing<br>';

    }

}

class ChildClass extends ParentClass {

    protected function init() {

        //child class initialization

        echo 'constructing child<br>';

    }

}

that way the child class can have a sort-of constructor, and the parent class's constructor will always execute. Is this bad practice?

A: 

After finalizing the constructor, you can't pass any variables to initializing function. It forces users of you class to use globals as settings for their child classes.

In Zend Framework using overridable init() is common practice, but I've never seen finalizing a constructor there.

valya
Really? I just tried it and I could pass a variable from the finalized constructor to the child initializing function and echo it
Carson Myers
oh, I mean, user can't pass any unforseen parameter
valya
However, ZF is moving to passing around config objects as a means of standardizing how parameters are passed between objects.
Noah Goodrich
Yeah, it's another solution, if he really wants to finalize his constructor
valya
+3  A: 

Declaring a final __construct ensures that no one who extends your class can implement a method with the same name. On the surface of it, this would seem like it would mean no one else can declare a constructor for sub-classes of this class, but this is not true, since the PHP 4 style of ClassName() still works just fine as an alternate name for the constructor. So really, declaring a constructor as final gets you nothing in PHP.

Mike
that's true, I hadn't considered that. Would the parent class's `__construct` method still be called though? Or would the child class's constructor of a different name just override it?
Carson Myers
Parent constructors are never called automatically. You would still have to call `parent::__construct()` or `parent::ClassName()` in the child class constructor.
Mike