PHP Destructor

A destructor is a special method in a class that is automatically called when an object is destroyed or goes out of scope. It is used to perform cleanup tasks, such as closing connections or releasing resources.

Defining a Destructor

<?php
class Database {
    public function __construct() {
        echo "Database connection established.\n";
    }

    // Destructor
    public function __destruct() {
        echo "Database connection closed.\n";
    }
}
?>

Using the Destructor

<?php
$db = new Database();
// The destructor will be called when $db goes out of scope
?>

Output:

Database connection established.
Database connection closed.

Explanation: This example demonstrates how to define a destructor in a class, which is automatically called when the object is destroyed, allowing for resource cleanup.