Is there any advantage to using __construct()
instead of the class's name for a constructor in PHP?
Example (__construct
):
class Foo {
function __construct(){
//do stuff
}
}
Example (named):
class Foo {
function Foo(){
//do stuff
}
}
Having the __construct
method (first example) is possible since PHP 5.
Moderator note: The question relates to functionality that was available in PHP 5. Since PHP 7.0, named constructors have been deprecated and removed in PHP 8.0.
The advantage is that you don't have to rename it if you rename your class. DRY.
Similarly, if you have a child class, you can call the parent constructor:
parent::__construct()
If further down the track you change the class the child class inherits from, you don't have to change the construct call to the parent.
It seems like a small thing, but missing changing the constructor call name to your parents' classes could create subtle (and not so subtle) bugs.
For example, if you inserted a class into your hierarchy, but forgot to change the constructor calls, you could start calling constructors of grandparents instead of parents. This could often cause undesirable results which might be difficult to notice.