The __destruct Method
The __destruct
function is a magic method in PHP that is automatically called when an object is removed from memory. This happens either when the script finishes execution or when the object is explicitly destroyed. The method is useful for freeing resources (for example, closing file descriptors or database connections).
Syntax
class MyClass {
public function __destruct() {
// destructor code
}
}
Example
A simple example of a class with a destructor that outputs a message when the object is destroyed:
<?php
class Test {
public function __destruct() {
echo 'Object destroyed';
}
}
$obj = new Test();
unset($obj); // Will call the destructor
?>
Execution result:
'Object destroyed'
Example
An example with resource freeing (closing a file):
<?php
class FileHandler {
private $file;
public function __construct($filename) {
$this->file = fopen($filename, 'r');
}
public function __destruct() {
if ($this->file) {
fclose($this->file);
echo 'File closed';
}
}
}
$handler = new FileHandler('example.txt');
// Working with the file...
unset($handler); // Will close the file automatically
?>
Execution result:
'File closed'
See Also
-
the
__construct
method,
which is the class constructor