Question

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.

Having a method with the same name as the class as constructor (second example) is possible from PHP version 4 until version 7.

Was it helpful?

Solution

I agree with gizmo, the advantage is so you don't have to rename it if you rename your class. DRY.

Similarly, if you have a child class you can call

parent::__construct()

to call the parent constructor. 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 heirachy, but forgot to change the constructor calls, you could started calling constructors of grandparents instead of parents. This could often cause undesirable results which might be difficult to notice.

Also note that

As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

Source: http://php.net/manual/en/language.oop5.decon.php

OTHER TIPS

__construct was introduced in PHP5. It is the way you are supposed to do it now. I am not aware of any advantages per se, though.

From the PHP manual:

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics

If you're on PHP5 I would recommend using __construct to avoid making PHP look elsewhere.

The main advantage I see for __construct, is that you don't have to rename your constructor if you change your class name.

Today, the accepted answer is obsolete.

Renaming classes is bad practice: you have to remember what and where to rename everytime you upgrade to newer version. Sometimes (like using Reflection or complex dependence structure) it can be impossible without radical refactoring. And this is accidental complexity you want to avoid. That's why namespaces were introduced into PHP. Java, C++ or C# don't use __construct, they use named constructor and there's no issue with them.

As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

Example

namespace Foo;
class Test {
  var $a = 3;

  function Test($a) {
    $this->a = $a;
  }

  function getA() {
    return $this->a;
  }
}

$test = new Test(4);
echo $test->getA(); // 3, Test is not a constructor, just ordinary function

Note that named constructors are not deprecated (PHP 5.5 today). However, you can't predict that your class won't be used in namespace, therefore __construct should be preffered.

Clarification about the bad practice mentioned above (for Dennis)

Somewhere in your code you could use ReflectionClass::getName(); when you rename the class, you need to remember where you used Reflection and check if the getName() result is still consistent in your app. The more you need to remember something specific, the more likely something is forgotten which results in bugs in the app.

The parents can't have control about all the classes in the world which depends on them. If allow_url_include is enabled, some other web might be using the class from your server, which may crash if you rename some class. It is even worse in compiled languages mentioned above: the library can be copied and bundled in other code.

There is no reason why to rename class:

  • if the class name conflicts, use namespaces
  • if the class responsibility shifts, derive some other class instead

In PHP classes in namespace, the method with the same name should be avoided anyway: intuitively it should produce an object created the class; if it does something else, why to give it the same name? It should be a constructor and nothing else. The main issue is that the behavior of such a method depends on namespace usage.

There is no issue with __construct constructors in PHP. But it wasn't the smartest idea to alter the named constructors.

The best advantage of using __contruct() instead of ClassName() is when extending classes. It is much easier to call parent::__construct() instead of parent::ClassName(), as it is reusable among classes and the parent can be changed easily.

In your example Foo::Foo is sometimes called a PHP 4 or old-style constructor because it comes from the days of PHP 4:

class Foo {
    // PHP 4 constructor
    function Foo(){
        //do stuff
    }
}

PHP 4 constructors will be deprecated but not removed in PHP 7. They will be no longer be considered as constructors in any situation in PHP 8. Future compatibility is definitely a big reason to not use this feature.

In PHP 5 the advantage would be that performance would be better. It will look for a constructor by the name of __construct first and if it doesn't find that, it will look for constructors by the name of className. So if it finds a constructor by the name __construct it does not need to search for a constructor by the name className.

Well it has been a few years since this question was asked, but I think I have to answer this one still, because things has changed and for readers in the future I want to keep the information up to date!


So in php-7 they will remove the option to create the constructor as a function with the same name as the class. If you still do it you will get a E_DEPRECATED.

You can read more about this proposal (the proposal is accepted) here: https://wiki.php.net/rfc/remove_php4_constructors

And a quote from there:

PHP 7 will emit E_DEPRECATED whenever a PHP 4 constructor is defined. When the method name matches the class name, the class is not in a namespace, and a PHP 5 constructor (__construct) is not present then an E_DEPRECATED will be emitted. PHP 8 will stop emitting E_DEPRECATED and the methods will not be recognized as constructors.

Also you won't get a E_STRICT in php-7 if you define a method with the same name as the class AND a __construct().

You can see this also here:

PHP 7 will also stop emitting E_STRICT when a method with the same name as the class is present as well as __construct.


So I would recommend you to use __construct(), since you will have less issues with this in the future.

Forward compatibility. There's always a chance that legacy code that's left in the language for backwards compatibility's sake will be removed in a future version.

If there is methods __construct and SameAsClassName method then __construct will be executed, SameAsClassName method will be skipped.

I think that the main reason is that is the language convention. You don't need to force a language to act like someone else.

I mean, in Objective-C you prefix the constructors with -init, for example. You can make your own constructor using your class name but why? Are ther some reason to use this schema instead of the language convention?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top