The __destruct() Function
__destruct() is a special class method that PHP calls automatically when an object is destroyed or when the script ends.
You can think of it as the counterpart of __construct(): one runs as an object begins its life, the other as that life ends.
Once a class has a __destruct() function, PHP will call it for you at the end of the script, with no call needed in your own code.
As with the constructor, the name begins with two underscores (__).
The next example puts both special functions together: __construct() runs when each object is created, and __destruct() runs when the script reaches its end:
Destructor Example
The __destruct() function displays each fruit's details once the script ends:
Output: PHP script
<?php
class Fruit {
public $name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "Name: " . $this->name . ". Color: " . $this->color .".<br>";
}
}
$apple = new Fruit('Apple', 'Red');
$banana = new Fruit('Banana', 'Yellow');
?>
Useful Tip
Tip: Constructors and destructors are worth using because they cut down on the code you have to write.