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.

// Namespaced classes do not recognize PHP 4 constructors
namespace NS;
class Filter {
 
    // Not a constructor , normal method
    function filter($a) {}
}



class Filter {
 
    // PHP 5: filter is a constructor
    // PHP 7: filter is a constructor and E_DEPRECATED is raised
    // PHP 8: filter is a normal method and is not a constructor; no E_DEPRECATED is raised
    function filter($a) {}
}
 
$filter = new ReflectionMethod('Filter', 'filter');
 
// PHP 5: bool(true)
// PHP 7: bool(true)
// PHP 8: bool(false)
var_dump($filter->isConstructor());


// function filter is not used as constructor in PHP 5+
class Filter {
    // PHP 5: E_STRICT "Redefining already defined constructor"
    // PHP 7: No error is raised
    // PHP 8: No error is raised
    function filter($a) {}
    function __construct() {}
}

// function filter is not used as constructor in PHP 5+
class Filter {
    function __construct() {}
 
    // PHP 5.0.0 - 5.2.13, 5.3.0 - 5.3.2: E_STRICT "Redefining already defined constructor"
    // PHP 5.2.14 - 5.2.17, 5.3.3 - 5.6: No error is raised
    // PHP 7: No error is raised
    // PHP 8: No error is raised
    function filter($a) {}
}

class Filter {
    // PHP 5: filter is a constructor
    // PHP 7: filter is a constructor and E_DEPRECATED is raised
    // PHP 8: filter is a normal method and is not a constructor; no E_DEPRECATED is raised
    function filter() {}
}
 
class FilterX extends Filter {
 
    function __construct() {
        // PHP 5: Filter::filter is called; no error
        // PHP 7: Filter::filter is called; no error
        // PHP 8: "Fatal error: Cannot call constructor"
        parent::__construct();
    }
 
}
 
new FilterX();
 

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

DMCA.com Protection Status