PHP OOP – Destructor

In PHP OOP, a destructor is a special method that is automatically called when an object is destroyed. The destructor method is used to perform any cleanup tasks that are necessary before the object is destroyed.

Here’s an example of a class with a destructor:

class Example {
    public function __construct() {
        echo "Object created.<br>";
    }
    
    public function __destruct() {
        echo "Object destroyed.<br>";
    }
}
$example = new Example(); // Output: Object created.
unset($example); // Output: Object destroyed.

In this example, the Example class has a constructor that is called when an object is created, and a destructor that is called when an object is destroyed. The constructor simply outputs a message to indicate that an object has been created, and the destructor outputs a message to indicate that an object has been destroyed.

To create an object of the Example class, we use the new keyword:

$example = new Example(); // Output: Object created.

When we no longer need the object, we can destroy it using the unset() function:

unset($example); // Output: Object destroyed.

This will destroy the object and call its destructor method.

In summary, the destructor in PHP OOP is a special method that is automatically called when an object is destroyed. It is used to perform any cleanup tasks that are necessary before the object is destroyed.