PHP 7 – PHP 4-Style Constructors are Deprecated

PHP 4 constructors were preserved in PHP 5 alongside the new __construct().PHP 4 constructors are methods that have the same name as the class they are defined in. Now, PHP 4-style constructors are being deprecated in favour of having only a single method (__construct()) to be invoked on object creation. And in PHP8 recognition for old constructors will be outright removed so it’s better to avoid PHP 4 style constructors.

Before PHP 5 and PHP 5 – class is defined within a namespace or if an __construct() method existed, then a PHP 4-style constructor was recognized as a plain method. If it was defined above an __construct() method, then an E_STRICT notice would be emitted, but still recognized as a plain method.

In PHP 7, if the class is not in a namespace and there is no __construct() method present, the PHP 4-style constructor will be used as a constructor but an E_DEPRECATED will be emitted.

In PHP 8, the PHP 4-style constructor will always be recognized as a plain method and the E_DEPRECATED notice will disappear.

By Arjun

I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.

1 reply on “PHP 7 – PHP 4-Style Constructors are Deprecated”

Would have been nice if you explained why this change is being implemented. It seems silly to break backwards compatibility and adherence to standard language conventions because of bugs in other places of the php language.

Personally, I find this to be a ridiculous change, especially since the only reasoning I’ve heard for doing this is because people don’t like changing the name of constructors when they change the name of classes. What php should do is implement a proper way to call a parents constructo; instead of parent::ClasName(), it should just be parent()… or behind the scenes have parent::_constructor() resolve to the class named constructor.

As for class name constructors not working in all instances, like for classes in namespaces, that is the bug that should be fixed, instead of changing the entire structure to this new style.

Leave a Reply

Your email address will not be published. Required fields are marked *