A destructor is a special method that is automatically called when an object is destroyed or goes out of scope. The destructor method is named __destruct() and can be used to perform cleanup tasks such as closing database connections, releasing resources, or any other actions that should be executed before an object is removed from memory.
Here's a basic example of a destructor in a PHP class:
<?php
class MyClass {
// Properties
public $name;
// Constructor
public function __construct($name) {
$this->name = $name;
echo "Object created. Hello, {$this->name}!";
}
// Destructor
public function __destruct() {
echo "Object destroyed. Goodbye, {$this->name}!";
}
}
// Creating an object of the MyClass class with constructor
$obj = new MyClass("John");
// Output: Object created. Hello, John!
// The destructor will be automatically called when the script ends or when the object goes out of scope.
// Output: Object destroyed. Goodbye, John!
?>
In this example, the MyClass has both a constructor (__construct()) and a destructor (__destruct()). When an object of the MyClass is created, the constructor is called, and when the script ends or when the object goes out of scope, the destructor is automatically called.
It's important to note that PHP automatically takes care of memory management, and usually, you don't need to explicitly use destructors. They are mainly used for resource cleanup or releasing connections.