PHP Destructors

Introduction to PHP Destructors

Destructor is a special function. The way the constructor is doing the function object is called, the same happens when the destructor function object is destroyed.

In some programming languages, objects are manually destroyed, but this work in PHP is done by a garbage collector. As soon as an object is free and there is no extra need then the garbage collector destroys it.

Syntax of PHP Destructor

Destructor in PHP is declared by __destruct () function. Its simple syntax is being given below.

<?php
function __destruct()
{
// Statements to be executed when object gets destroyed.
}
?>

Like the Constructor function, the Destructor function is also defined by double underscore function.

Example of PHP Destructor

An example of the PHP destructor function is being given below.

<?php
class myClass
{
// Constructor function
function __construct()
{
echo "Object is created...<br />";
}
// Destructor function
function __destruct()
{
// Display message when object gets destroyed.
echo "Object is destroyed";
}
}
$myclass = new myClass;
?>