A destructor is invoked when an object is destroyed or when the script is stopped or exited.
If you define a __destruct()
function, PHP will automatically call this function at the end of the script.
Note that the destructor function begins with two underscores (__
).
In the example below, the __construct()
function is automatically called when an object is created from a class, and the __destruct()
function is automatically called at the end of the script.
<?php class Fruit { public $name; public $color; function __construct($name) { $this->name = $name; } function __destruct() { echo “The fruit is {$this->name}.”; } } $apple = new Fruit(“Apple”); ?> |
Another example:
<?php class Fruit { public $name; public $color; function __construct($name, $color) { $this->name = $name; $this->color = $color; } function __destruct() { echo “The fruit is {$this->name} and the color is {$this->color}.”; } } $apple = new Fruit(“Apple”, “red”); ?> |
Tip: Constructors and destructors are very useful for reducing code by automating initialization and cleanup tasks! |