4

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.

3
  • 1
    The __construct constructors were already in php5 so if you have a php4 codebase then there is a lot more to fix..
    – tkausl
    Mar 14, 2016 at 0:12
  • @tkausl: the fact the new form was available since PHP5 does not mean older PHP code from all over the world, in every company or organization, was immediately ported to the new style. Making a language change in a non-backwards compatible manner is always debatable.
    – Doc Brown
    Mar 14, 2016 at 12:21
  • wiki.php.net/rfc/remove_php4_constructors has more info. There is a great deal of debate concerning this and other proposed bc changes. Dropping the 'var' keyword is another one.
    – Cerad
    Mar 14, 2016 at 13:10

1 Answer 1

3

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.

3
  • 2
    There are no constructors in C. But I think Java would be worth mentioning.
    – 5gon12eder
    Mar 14, 2016 at 18:15
  • Python also binds the class name as its constructor
    – Jack
    Mar 15, 2016 at 5:55
  • @Jack In Python you call ClassName() to make an object but you name the constructor-thing __init__()
    – Weaver
    Mar 15, 2016 at 7:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.