2

The history of PHP says that the older versions of PHP use the class name as a method for a constructor for the same class.

The PHP 5.3.3 documentation says that:

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 A;

 class classOne{
   public function methodOne(){}
   public function methodTwo(){}
   public function classOne(){} //Constructor
 }

 class classTwo{
   public function methodOne(){}
   public function methodTwo(){}
   public function classTwo(){} //Constructor
 }

So according to this documentation, classOne() and classTwo() are not considered as constructors? What is the reasoning behind this? Can anyone tell me?

Reference Link

1000Nettles
  • 2,314
  • 3
  • 22
  • 31

1 Answers1

2

Regarding why this rule applies for namespaced classes vs. non-namespaced, PHP 5.3 introduced namespaces. If you were upgrading from an older PHP version, you would have non-namespaced classes to look after, potentially using the old style way of creating constructors.

They want to enforce that you are developing within modern PHP principles and that you are also using the new conventions. PHP at this point is committed to removing old-style constructors completely, which we have seen as they are deprecated in PHP 7 and will be removed in a future version.

Finally, the reasoning behind dropping this convention altogether is that it is more error-prone. Using the DRY principles, if one was to change a class name while refactoring, forgetting to change the name of the constructor, it could have subtle and not-so-subtle repercussions.

If you are extending a class and want to call its constructor, it is also more error-prone if their parent class's name changes. For further reading:

https://stackoverflow.com/a/29794401/823549

and

https://stackoverflow.com/a/217876/823549.

Pradeep
  • 9,667
  • 13
  • 27
  • 34
1000Nettles
  • 2,314
  • 3
  • 22
  • 31