PHP OOP - Destructor

In PHP (Object-Oriented Programming), a destructor is a special method that is automatically called when an object is destroyed or goes out of scope. It's commonly used to perform cleanup operations such as closing database connections or releasing resources.

Syntax of Destructor in PHP

class MyClass { public function __construct() { echo "Constructor called<br>"; } public function __destruct() { echo "Destructor called<br>"; } } $obj = new MyClass(); // When the script ends or $obj is unset, the destructor is automatically invoked.

Key Points

  • The destructor method is named __destruct().

  • PHP automatically calls the destructor when:

    • The object is explicitly destroyed using unset().

    • The script ends and the object is no longer referenced.

  • Unlike constructors, destructors do not accept parameters.

Example

class FileHandler { private $file; public function __construct($filename) { $this->file = fopen($filename, "w"); echo "File opened.<br>"; } public function writeData($data) { fwrite($this->file, $data); } public function __destruct() { fclose($this->file); echo "File closed.<br>"; } } $handler = new FileHandler("example.txt"); $handler->writeData("Hello, World!"); // File will be closed automatically when $handler is destroyed