Chris
Chris

Reputation: 6233

What is the difference between the two types of class constructors in PHP?

What exactly is the difference in PHP classes when using the __construct constructor and when using the name of the class as constructor?

For example:

class Some
{
     public function __construct($id)
     {
           ....
     }
     ....
}

OR

class Some
{
      public function Some($id)
      {
            ....
      }
      ....
}

Upvotes: 7

Views: 262

Answers (1)

John Conde
John Conde

Reputation: 219804

The top is the new way it is done in PHP as of version 5.0 and is how all new code should be written. The latter is the old PHP 4 way and is obsolete. At some point it will be completely deprecated and removed from PHP altogether.

Update

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.

<?php
namespace Foo;
class Bar {
    public function Bar() {
        // treated as constructor in PHP 5.3.0-5.3.2
        // treated as regular method as of PHP 5.3.3
    }
}
?>

Upvotes: 13

Related Questions