PHP Destructor
Summary: in this tutorial, you will learn about the PHP destructor and use it to clean up the resources when the object is deleted.
Introduction to the PHP destructor
Like the constructor, PHP allows you to define a destructor for a class using a special method __destruct()
like this:
class className
{
public function __destruct()
{
//...
}
}
Code language: HTML, XML (xml)
Unlike a constructor, a destructor doesn’t accept any argument. The destructor is automatically invoked before an object is deleted. It happens when the object has no reference or when the script ends.
PHP destructor example
The following simple FileUtil
class demonstrates how to use the destructor to close a file handle:
class File
{
private $handle;
private $filename;
public function __construct($filename, $mode = 'r')
{
$this->filename = $filename;
$this->handle = fopen($filename, $mode);
}
public function __destruct()
{
// close the filehandle
if ($this->handle) {
fclose($this->handle);
}
}
public function read()
{
// read the file contents
return fread($this->handle, filesize($this->filename));
}
}
$f = new File('./test.txt');
echo $f->read();
Code language: HTML, XML (xml)
How it works.
- First, define the
File
class with the constructor that accepts two arguments:$filename
and$mode
. By default, theFile
class opens the file for reading. - Second, open the file and assign the file handle to the
$handle
property in the constructor. - Third, close the file handle in the destructor.
- Fourth, return the file contents from the
read()
method.
Summary
- Use the
__destruct()
to define a destructor for a class. - PHP automatically invokes the destructor when the object is deleted or the script is terminated.