Methods with the same name as their class will not be constructors in a future version of PHP

Lots of users are facing this issue whenever they upgrade their PHP7. Because PHP7 does not allow the same class name as the constructor and show some warning. In PHP 4 we can define a method of a class with the name of its class as a constructor. This is old-style constructor function or you can say, deprecated constructor.

How to solve this error?

First lets check the below code-

Methods with the same name as their class will not be constructor
<?php
class foo {
	
    function foo() {
        echo 'I am old style constructor of foo class';
    }
}
?>

If your code has this type of class and whenever you use PHP7 you will get the below warning-

PHP Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo has a deprecated constructor in

So PHP7 has __construct() method instead of PHP4 style same class name use as a constructor. Replace all of your classes that use PHP4 style constructor with __construct () .

<?php
class foo {
	
    function __construct(){
        echo 'I am new style constructor of foo class';
    }
}
?>

Or you can use following <code data-enlighter-language="generic" class="EnlighterJSRAW">error_reporting in your config file:

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);

This is not recommended because in future PHP version, this method can be totally removed.

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment