Table of Content
A destructor in a PHP class runs when an object is no longer needed. It frees resources and cleans up tasks before the object is removed from memory.
We will cover the following topics:
- A class destructor in PHP.
- How it works.
- It’s syntax.
- Examples.
Let’s start with the definition.
Understand What a Destructor Is in PHP
A destructor in a PHP class is a special method that runs when an object is about to be removed from memory in OOP PHP.
It has the name __destruct(). PHP calls it automatically when an object goes out of scope or when the script ends.
Here is an example:
class People {
public function __construct() {
echo "Object of people class created.";
}
public function __destruct() {
echo "Object of people class destroyed.";
}
}PHP calls the destructor automatically when the script ends or when there are no more references to the object. This helps prevent memory leaks.
So, when should you use the class destructor in PHP?
You use the class destructor to:
- Close database connections.
- Release file handles.
- Clear session data.
- Log actions before an object is destroyed.
Let’s move on to the following section to understand how it works.
How Does a Destructor Work?
It runs automatically when an object completes its tasks. PHP calls the destructor when the object goes out of scope or when the script ends.
The destructor helps clean up resources before the object is removed from memory.
Here is how it calls the destructor for the following reasons:
- When an object is unset.
- When the script ends.
- If an object goes out of scope.
Here are examples for each one:
Unset the object: PHP immediately calls the destructor If you manually unset an object.
class FlatCodingTest {
public function __destruct() {
echo "Destructor called\n";
}
}
$obj = new FlatCodingTest();
unset($obj); The script ends: It calls its destructor before shutting down, If an object still exists at the end of the script.
class FlatCodingTest {
public function __destruct() {
echo "Destructor called\n";
}
}
$obj = new FlatCodingTest(); It goes out of scope: The destructor runs when the function finishes If an object is created inside a function.
function createObject() {
$obj = new FlatCodingTest();
}
createObject();Let’s move on to the section below to learn how to free resources using the PHP destructor.
Freeing Resources with a Class Destructor in PHP
The destructor can close a database connection if an object has it open. For example:
class FC_Database {
private $fc_conn;
public function __construct() {
$this->fc_conn = new mysqli("localhost", "username", "password", "database");
}
public function __destruct() {
if ($this->fc_conn) {
$this->fc_conn->close();
echo "Database connection closed";
}
}
}
The destructor closes the connection and prints a message when the object is no longer needed.
Here is another example to release file handles:
class Palmet_File {
private $file;
public function __construct($filename) {
$this->file = fopen($filename, "w");
}
public function __destruct() {
fclose($this->file);
echo "File has been closed\n";
}
}This PHP class opens a file for writing when created. The destructor closes the file and prints a message when the object no longer exists.
We can use it to clear session data. Here is an example:
class SessionManager {
public function __construct() {
session_start();
}
public function __destruct() {
session_unset();
session_destroy();
echo "Session destroyed\n";
}
}
Here, the destructor clears and destroys the session when the object has finished its task.
Wrapping Up
A destructor in PHP is a special method that runs when an object is no longer needed. PHP calls the destructor automatically when an object goes out of scope or when the script ends.
Here is a quick recap of what you learned in this article:
- A destructor is a method named
__destruct()that runs when an object is about to be destroyed. - It helps you manage resources such as:
- Close database connections
- Release files
- Clear session data.
- PHP calls a destructor automatically in the following cases:
- When an object is unset.
- When it goes out of scope.
- If the script ends.
- Using a destructor prevents memory leaks and makes sure resources are properly released.
FAQ’s
How to Destroy a Class in PHP?
class FCExample {
public function __destruct() {
echo "Object is destroyed\n";
}
}
$fobj= new FCExample();
unset($fobj); // Calls the destructor
What Is the Purpose of a Destructor in PHP?
When Is a Destructor Called in PHP?
- When an object is unset using unset($object).
- When the script ends and the object still exists.
- If an object goes out of scope, like when a function finishes.
Can I Use a Destructor to Close a Database Connection in PHP?
class FC_Database {
private $fc_conn;
public function __construct() {
$this->fc_conn = new mysqli("localhost", "username", "password", "database");
}
public function __destruct() {
if ($this->fc_conn) {
$this->fc_conn->close();
echo "Database connection closed";
}
}
}
$db = new FC_Database();
Similar Reads
The filter_input_array() filters multiple inputs in PHP at once. It helps you to clean and validate data. Understand the filter_input_array…
You may need to get part of a text when you work with text in PHP. The mb_substr gives you…
PHP arrays are lists or maps that contain multiple values grouped by array keys. They may include integers, strings, booleans,…
MySQL Prepared Statements in PHP are an important tool for ensuring security and optimization. They safeguard against SQL injection attacks,…
In PHP, if you're working with XML files, you’ll probably work with DOMDocument. It is a powerful class, enabling you…
The abs() function in PHP gives you a number without its sign — it always returns a positive value. That…
PHP developers relied on class inheritance to share functionality before the OOP interface, but this approach had limits. It solves…
If you are working with PHP and MySQL, one of the first tasks you may need is to create a…
When you start working with PHP, you’ll soon need access to variables from multiple places in your code. For this,…
File Handling in PHP is an important tool especially when you need to manage files such as reading, writing, or…