In this tutorial, we will learn about PHP Destructor. The destructor method is totally reverse of the constructor method. PHP destructor does not return any value. In case we create __destructor function in class, PHP will automatically call the destructor function if there are no other references to a particular object or at the end of the script.
Please Note, that the desructor function starts with two underscores (__). for e.g. __destruct()
Here an example program to show how to define destructor in PHP.
<?php
class Example {
//defing a constructor
function __construct() {
echo "This is constuctor method.<br>";
}
//defing a normal method
function show(){
echo "This is show method.<br>";
}
//defing a destructor
function __destruct() {
echo "The is destructor method.<br>";
}
}
$obj = new Example();
$obj->show();
$obj->show();
$obj->show();
?>
The destructor will be called even if script execution is stopped using exit() or die() function.
Difference b/w Constructor and PHP Destructor:
Constructor | Destructor |
---|---|
It Allocates Memory | It Deallocates Memory |
Get called at the time of class is instantiated | Get called at the time of deletion of the object |
Name of function is _construct(). | Name of function is _destruct() |
Can accept parameters | Can not accept parameters |
Constructors can be overloaded | Destructors can not be overloaded |