Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to declare a class's ctor 'final' in PHP?

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?

like image 440
Carson Myers Avatar asked Jan 03 '10 01:01

Carson Myers


1 Answers

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.

like image 74
Mike Avatar answered Oct 13 '22 16:10

Mike