Reputation: 1433
Is it possible - in PHP - to "disable" the functionality of overriding the constructor of a class?
Just to make the scenario clear: I've an abstract class A, with a constructor. This constructor is essential for the working of the class. Then I have some "siblings", that "extend" the abstract class A. They - obiously - have to extend that class, but I don't want them to touch the constructor.
I know it's possible to call parent::__construct(), but that way I don't force that pattern. In the case a colleague of mine is implementing a new class that extends my abstract class, I don't want there to be no confusion. Of-couse everything is documented, but y'all know how it goes when it comes to reading stuff ;-)
Any ideas on how to disable the overriding of the constructor? (In that case I'd make an abstract init() method that can be override, but my "abstract constructor" will cal that one). Or any other ideas to implement this wanted situation?
Thanks! Niek
Upvotes: 3
Views: 2128
Reputation: 8480
You can declare the constructor as final when your class is abstract.
public final function __construct(){}
In this constructor you can call you init() method.
Upvotes: 9
Reputation: 1087
You could check what class invoked the constructor and if was the parent class you execute your construct code, otherwise you not
Upvotes: 1
Reputation:
Move code from constructor to another method. Constructors shouldn't contain any logic, only initialization of variables by arguments, given to constructor.
http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/
Upvotes: 1