A destructor in PHP is a special method defined using __destruct()
. It is automatically called when an object is destroyed or the script ends. Destructors are used for cleanup tasks like closing files or database connections. They do not take any parameters. Only one destructor can be defined per class.
1. Basic Destructor Example
class Test {
public function __construct() {
echo "Constructor called
";
}
public function __destruct() {
echo "Destructor called";
}
}
$obj = new Test();
// Destructor runs automatically at the end of script
File: destructor_basic.php
2. Destructor with Resource Cleanup
class FileHandler {
private $handle;
public function __construct($filename) {
$this->handle = fopen($filename, "w");
echo "File opened
";
}
public function write($text) {
fwrite($this->handle, $text);
}
public function __destruct() {
fclose($this->handle);
echo "File closed";
}
}
$file = new FileHandler("demo.txt");
$file->write("Hello, world!");
File: destructor_file.php
Destructor Rules
Rule | Description |
---|---|
Function name | __destruct() |
No parameters | Destructors can’t accept parameters |
Runs automatically | Called at end of script or when object unset |
Only one per class | You can define only one destructor per class |