Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
      {
            ....
      }
      ....
}
like image 204
Chris Avatar asked May 14 '12 18:05

Chris


1 Answers

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
    }
}
?>
like image 101
John Conde Avatar answered Sep 21 '22 00:09

John Conde