A destructor method helps clean up when an object is no longer needed. It runs automatically to free resources or do final tasks.
0
0
Destructor method in PHP
Introduction
When you want to close a file or database connection automatically.
When you need to release memory or other resources before an object is destroyed.
When you want to log or track when an object is removed.
When cleaning up temporary data created by an object.
When you want to ensure some code runs at the end of an object's life.
Syntax
PHP
<?php class ClassName { public function __destruct() { // cleanup code here } } ?>
The destructor method is named __destruct with two underscores.
It does not take any parameters and cannot return a value.
Examples
This example shows a destructor that prints a message when the object is destroyed.
PHP
<?php class Logger { public function __destruct() { echo "Closing logger.\n"; } } $log = new Logger(); ?>
This example opens a file when the object is created and closes it automatically when the object is destroyed.
PHP
<?php class FileHandler { private $file; public function __construct($filename) { $this->file = fopen($filename, 'w'); } public function __destruct() { fclose($this->file); echo "File closed.\n"; } } $fh = new FileHandler('test.txt'); ?>
Sample Program
This program shows a connection opening message when the object is created and a closing message when the object is destroyed automatically at the end.
PHP
<?php class Connection { public function __construct() { echo "Connection opened.\n"; } public function __destruct() { echo "Connection closed.\n"; } } $conn = new Connection(); echo "Doing some work...\n"; // When script ends or object is no longer used, destructor runs ?>
OutputSuccess
Important Notes
The destructor runs automatically when the object is no longer referenced or at the end of the script.
You cannot call the destructor method directly; PHP calls it for you.
Use destructors to avoid forgetting to release resources manually.
Summary
Destructor methods clean up when an object is destroyed.
They are named __destruct and run automatically.
Use them to close files, connections, or free resources safely.