PHP Destructor
Cleaning up when objects are destroyed
๐งน What is a Destructor?
A destructor is a special method that automatically runs when an object is destroyed or the script ends. It's used for cleanup tasks like closing files, database connections, or freeing resources.
<?php
class FileHandler {
public $filename;
public function __construct($filename) {
$this->filename = $filename;
echo "File opened: $filename
";
}
public function __destruct() {
echo "File closed: $this->filename
";
}
}
$file = new FileHandler("data.txt");
// Destructor runs automatically at script end
?>
Output:
File opened: data.txt
File closed: data.txt
Destructor Features
Auto-Execute
Runs when object is destroyed or script ends
public function __destruct() {
// Cleanup code
}
Cleanup Tasks
Close connections and free resources
public function __destruct() {
$this->close();
}
No Parameters
Destructors cannot accept parameters
// Correct
public function __destruct() {
}
Timing
Called when no references to object exist
unset($obj);
// Destructor runs
๐น Basic Destructor
The destructor method is named
__destruct()
with two underscores. It's automatically called when the object is no longer needed or when the script finishes execution.
<?php
class Message {
public $text;
public function __construct($text) {
$this->text = $text;
echo "Object created: $text
";
}
public function __destruct() {
echo "Object destroyed: $this->text
";
}
}
$msg1 = new Message("Hello");
$msg2 = new Message("World");
echo "Script running...
";
// Destructors run automatically at end
?>
Output:
Object created: Hello
Object created: World
Script running...
Object destroyed: World
Object destroyed: Hello
๐น Manual Object Destruction
You can manually destroy an object using
unset()
. This immediately triggers the destructor instead of waiting for the script to end.
<?php
class Connection {
public $name;
public function __construct($name) {
$this->name = $name;
echo "Connection opened: $name
";
}
public function __destruct() {
echo "Connection closed: $this->name
";
}
}
$conn = new Connection("Database");
echo "Working with connection...
";
unset($conn); // Manually destroy object
echo "After unset
";
?>
Output:
Connection opened: Database
Working with connection...
Connection closed: Database
After unset
๐น Destructor for Resource Management
Destructors are commonly used to ensure resources like file handles or database connections are properly closed, preventing memory leaks and resource exhaustion.
<?php
class Logger {
private $logFile;
private $filename;
public function __construct($filename) {
$this->filename = $filename;
$this->logFile = fopen($filename, 'a');
echo "Log file opened: $filename
";
}
public function write($message) {
if ($this->logFile) {
fwrite($this->logFile, date('Y-m-d H:i:s') . " - $message\n");
echo "Logged: $message
";
}
}
public function __destruct() {
if ($this->logFile) {
fclose($this->logFile);
echo "Log file closed: $this->filename
";
}
}
}
$logger = new Logger("app.log");
$logger->write("Application started");
$logger->write("User logged in");
// Destructor automatically closes file
?>
Output:
Log file opened: app.log
Logged: Application started
Logged: User logged in
Log file closed: app.log
๐น Practical Example
This example demonstrates how constructors and destructors work together to manage the lifecycle of an object from creation to destruction.
<?php
class Session {
public $sessionId;
public $username;
public function __construct($username) {
$this->sessionId = uniqid();
$this->username = $username;
echo "Session started for $username (ID: $this->sessionId)
";
}
public function activity($action) {
echo "$this->username performed: $action
";
}
public function __destruct() {
echo "Session ended for $this->username (ID: $this->sessionId)
";
}
}
$session = new Session("Alice");
$session->activity("Viewed dashboard");
$session->activity("Updated profile");
echo "Logging out...
";
// Destructor runs automatically
?>
Output:
Session started for Alice (ID: 65c7f8a9b1234)
Alice performed: Viewed dashboard
Alice performed: Updated profile
Logging out...
Session ended for Alice (ID: 65c7f8a9b1234)