Old-Style Constructor is not Interpreted as Constructor in PHP 8.0

Old-Style Constructor is not Interpreted as Constructor in PHP 8.0

An old-style constructor is a method which has the same name as the class. Old-style constructors were used in PHP 4.

In PHP 5 and PHP 7, we can use old-style constructors in some cases. In these PHP versions, old-style constructor is interpreted as constructor if a class is in the global namespace and the __construct method is not defined. PHP 7 also emits a deprecation warning (E_DEPRECATED) if an old-style constructor is defined.

Let's say we have a User class with old-style constructor. This class is in the global namespace and the __construct method is not defined. Note that a class belongs to the global namespace if namespace is not declared.

User.php

<?php

class User
{
    public function User()
    {
        echo 'Constructor';
    }
}

We create an instance of a User class:

main.php

<?php

require_once 'User.php';

$user = new User();

If we run this code snippet in PHP 7, we will get a deprecation warning and a string Constructor will be printed.

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; User has a deprecated constructor in User.php on line 3
Constructor

Since PHP 8.0, old-style constructor is not interpreted as constructor. It means that running previous code snippet in PHP 8.0 or newer versions, nothing will be printed. The __construct method should be used instead.

User.php

<?php

class User
{
    public function __construct()
    {
        echo 'Constructor';
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.