Why should I use
function __construct() instead of
function className() in PHP 5?
My guess would be that by the time object-oriented capability was being added to PHP, the designers were looking at Python.
The __ magic methods/functions seem to be a consistent theme in PHP (for once!). One advantage of using
ClassName() as a constructor is if you change the name of the class, you don’t need to update the constructor.
Because php5 wanted to be more like python.
I kid, I kid…
Having a standard method for standard actions, like construction, is a reasonable solution. It’s the same reason that in C# classes, when you extend a class, you use
base for calling base class constructors instead of a named object: it simplifies code and makes maintenance easier.
Because it has been unified with the __destruct() method and other special methods beginning with two underscores for example __get, __sleep, __serialize
By doing so always, you can invoke the constructor from the super (base-)class without having to know its name. This is very useful for class tree maintenance, because you don’t want to have to update all your classes just because you re-arrange your class trees
and…just guessing.. if all classes name their constructors identically __construct(), in theory a constructor could be inherited from a superclass without any required definition. This makes sense in class trees where there are intermediate abstract classes, and in constructs like in objective C where default constructor behaviour is derived entirely from class metadata and therefore (in priciple!) would need no coding at all.
Old question, but I’ll bite since no one has actually answered the actual question yet.
function className() is a PHP4-style constructor.
function __construct() is a PHP5-style constructor.
You should use the latter because the former is deprecated and may be removed from the language.
Also, the former may or may not ignore various PHP5 OO concepts, such as the public/private visibility operators. Not that you’d want to make the constructor private if you weren’t using the Singleton or Factory patterns.