PHP Constructors and destructors
A constructor is a special method in a class. It is used to auto initialize property, methods, etc while using a class’s object. This constructor method is applicable to every method of consists of class.
The constructor function named __construct(), If the current class extending a parent class and It want to use the construct method of the parent class. Then It uses parent::__construct() with-in child class.
Using constructor on a simple class
<?php
class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
}
}
// In BaseClass constructor
$obj = new BaseClass();
?>
Using constructor with a parent class
<?php
class SubClass extends BaseClass {
function __construct() {
parent::__construct();
print "In SubClass constructor\n";
}
}
// In BaseClass constructor
// In SubClass constructor
$obj = new SubClass();
?>
Warning:
Old style constructors are DEPRECATED in PHP 7.0 and will be removed in a future version. You should always use __construct() in new code.
Unlike with other methods, PHP will not generate an E_STRICT level error message when __construct() is overridden with different parameters than the parent __construct() method has.
Destructor
PHP also provides destructor methods alike other object-orient programming languages, I.e Java, C++, etc. The destruct method is used to stop the auto initialized resource of class.
Parent destructor is not automatically run. To run parent destructor explicitly call parent::__destruct() in destructor method.
Note:
-
If HTTP headers already sent in the script then destructor will be shutdown.
-
While you will try to use exception handling with a destructor, It will cause a fatal error during script execution.