Destructor in PHP

Destructor in PHP : PHP destructor allows you to clean up resources before PHP releases the object from the memory. For example, you may create a file handle in the constructor and you close it in the destructor.

To add a destructor to a class, you just simply add a special method called __destruct() as follows:

  • Unlike a constructor, a destructor cannot accept any argument.
  • Object’s destructor is called before the object is deleted. It happens when there is no reference to the object or when the execution of the script is stopped by the exit() function.

The following simple FileUtil class demonstrates how to use the destructor to close a file handle. (Check it out the PHP File I/O tutorial to learn how to deal with files in PHP).

 <? php
class FileUtil{
private $handle;
private $filename;
/**
* inits file util with filename and mode
* @param string $filename
* @param string $mode
*/
public function __construct($filename,$mode){
$this->filename = $filename;
$this->handle = fopen($filename, $mode);
}
/**
* close the file handle
*/
public function __destruct(){
if($this->handle){
fclose($this->handle);
}
}
/**
* display file content
*/
public function display(){
echo fread($this->handle, filesize($this->filename));
}
}
$fu = new FileUtil(‘./test.txt’, ‘r’);
$fu->display();  ?> 
Scroll to Top