
Originally Posted by
ahundiak
Suppose you are designing a class which you know will be routinely extended. The __construct method accepts several arguments. You know the extended classes will usually want to do some sort of custom initialization.
Is it better to:
1. Have the extended class override the constructor keeping in mind that you need to keep the constructor signature intact.
or
2. Have the base constructor call an init() method once it is complete. The extended class will then override init().
or
3. A different approach
3.
NO Function does more than one thing in polymorphic code. The construct function exists to set the start state of the object. This means attach the parameters to the members of the object. Nothing else.
The fact that you are considering having the object need an init strongly indicates an overworked construct function. Construct really doesn't do much. In PHP you can't do this
PHP Code:
class MyClass {
protected $foo = new Bar();
}
The __construct function provides the workaround here.
PHP Code:
class MyClass {
protected $foo = null;
public function __construct() {
$this->foo = new Bar();
}
}
And honestly, that sort of thing is the only thing __construct functions should EVER do.
If you have tasks that you normally do as the object does then use a start function. Yes, this is clumsy
PHP Code:
$myObject = new myClass();
$myObject->start();
But there are going to arise times sooner or later when you'll wish that you could do something between the instantiation of the object and the running of whatever those typical start up tasks are.
Bookmarks