According to the PHP5 manual, __construct()
was introduced in PHP5 as a replacement for SameAsClassName()
constructors, and from PHP7, the old style is marked as deprecated, so in future versions, SameAsClassName()
will not be allowed any more.
I am just wondering about the rationale about this decision. The manual does not give any reasons for that change. What are the advantages of the using __construct() vs SameAsClassName() ?
Sidenote: in my code-base where there are about 2000 classes, this change causes the need for renaming every class manually to the __construct.
1 Answer 1
The change may have been part of a larger scheme to distinguish special functions from regular functions. In the same page you linked, they describe the special function __destruct
which previously had no analogue.
The idiom of a function of the same name as the class is the constructor isn't overly widespread outside of Java/C++/C#.
These reasons combined may have been enough to warrant the overhaul of the class system in that major release of the language.
The naming is likely due to that the double underscore __
is commonly used for implementation or language detail in languages like Python, C, and C++ — following suit there is unsurprising.
If you want a definitive answer, go spelunk the list archives and hope it wasn't discussed in private or in person.
-
2There are no constructors in C. But I think Java would be worth mentioning.5gon12eder– 5gon12eder2016年03月14日 18:15:04 +00:00Commented Mar 14, 2016 at 18:15
-
Python also binds the class name as its constructorJack– Jack2016年03月15日 05:55:53 +00:00Commented Mar 15, 2016 at 5:55
-
@Jack In Python you call ClassName() to make an object but you name the constructor-thing __init__()Weaver– Weaver2016年03月15日 07:49:00 +00:00Commented Mar 15, 2016 at 7:49
__construct
constructors were already in php5 so if you have a php4 codebase then there is a lot more to fix..