WikiGalaxy

Personalize

PHP Destructors

Introduction to Destructors:

In PHP, destructors are special methods that are automatically called when an object is destroyed. This can happen when the script ends, the object is unset, or the object goes out of scope.

Purpose of Destructors:

Destructors are primarily used for clean-up purposes, such as closing database connections, releasing resources, or writing final data to a log file.


<?php
class MyClass {
    function __construct() {
        echo "Constructor called.\n";
    }

    function __destruct() {
        echo "Destructor called.\n";
    }
}

$obj = new MyClass();
?>
    

Example Explanation:

This example demonstrates the basic use of a destructor in PHP. The destructor is called automatically when the object $obj is destroyed.

Console Output:

Constructor called. Destructor called.

Resource Management

Using Destructors for Resource Management:

Destructors can be used to free up resources such as file handles or database connections when they are no longer needed.


<?php
class FileHandler {
    private $file;

    function __construct($filename) {
        $this->file = fopen($filename, "w");
    }

    function write($data) {
        fwrite($this->file, $data);
    }

    function __destruct() {
        fclose($this->file);
        echo "File closed.\n";
    }
}

$handler = new FileHandler("example.txt");
$handler->write("Hello, World!");
?>
    

Example Explanation:

In this example, the destructor ensures that the file is properly closed when the FileHandler object is destroyed, preventing any resource leaks.

Console Output:

File closed.

Database Connection Cleanup

Using Destructors for Database Cleanup:

Destructors can be used to close database connections, ensuring that no open connections remain when the script ends.


<?php
class Database {
    private $connection;

    function __construct($host, $user, $pass, $dbname) {
        $this->connection = new mysqli($host, $user, $pass, $dbname);
    }

    function query($sql) {
        return $this->connection->query($sql);
    }

    function __destruct() {
        $this->connection->close();
        echo "Database connection closed.\n";
    }
}

$db = new Database("localhost", "root", "", "test_db");
$db->query("SELECT * FROM users");
?>
    

Example Explanation:

This example illustrates how a destructor can be used to close a database connection, ensuring that all resources are freed when the Database object is destroyed.

Console Output:

Database connection closed.

Logging with Destructors

Using Destructors for Logging:

Destructors can be used to log messages or events when an object is destroyed, which can be useful for debugging or auditing purposes.


<?php
class Logger {
    private $logfile;

    function __construct($filename) {
        $this->logfile = fopen($filename, "a");
    }

    function log($message) {
        fwrite($this->logfile, date("Y-m-d H:i:s") . " - " . $message . "\n");
    }

    function __destruct() {
        fwrite($this->logfile, "Logger shutdown.\n");
        fclose($this->logfile);
    }
}

$logger = new Logger("app.log");
$logger->log("Application started.");
?>
    

Example Explanation:

This example shows how a destructor can be used to log a shutdown message, ensuring that all log entries are properly recorded before the file is closed.

Console Output:

Logger shutdown.

Session Management with Destructors

Using Destructors for Session Management:

Destructors can be employed to manage sessions, performing tasks like saving session data or logging session termination.


<?php
session_start();

class SessionManager {
    function __destruct() {
        session_write_close();
        echo "Session data saved.\n";
    }
}

$session = new SessionManager();
$_SESSION['user'] = 'JohnDoe';
?>
    

Example Explanation:

In this example, the destructor ensures that session data is saved when the SessionManager object is destroyed, maintaining session integrity.

Console Output:

Session data saved.

Destructor with Inheritance

Using Destructors with Inheritance:

When using inheritance, destructors in derived classes can be used to perform additional cleanup tasks specific to the subclass.


<?php
class BaseClass {
    function __destruct() {
        echo "BaseClass destructor called.\n";
    }
}

class DerivedClass extends BaseClass {
    function __destruct() {
        echo "DerivedClass destructor called.\n";
        parent::__destruct();
    }
}

$obj = new DerivedClass();
?>
    

Example Explanation:

In this example, the destructor in DerivedClass calls the destructor of its parent class BaseClass, ensuring that both destructors are executed.

Console Output:

DerivedClass destructor called. BaseClass destructor called.

Dynamic Object Destruction

Dynamic Destruction of Objects:

Objects can be dynamically destroyed using the unset() function, triggering the destructor immediately.


<?php
class SampleClass {
    function __destruct() {
        echo "SampleClass destructor called.\n";
    }
}

$obj = new SampleClass();
unset($obj);
echo "Object unset.\n";
?>
    

Example Explanation:

This example demonstrates how using unset() on an object triggers its destructor, allowing for immediate resource cleanup.

Console Output:

SampleClass destructor called. Object unset.

Destructor and Exception Handling

Destructors and Exception Handling:

Destructors are also called when an exception is thrown, allowing for cleanup even in error conditions.


<?php
class ErrorHandling {
    function __destruct() {
        echo "ErrorHandling destructor called.\n";
    }
}

try {
    $obj = new ErrorHandling();
    throw new Exception("An error occurred.");
} catch (Exception $e) {
    echo $e->getMessage() . "\n";
}
?>
    

Example Explanation:

In this example, the destructor is called even when an exception is thrown, ensuring that resources are cleaned up despite the error.

Console Output:

An error occurred. ErrorHandling destructor called.

Destructor and Global Variables

Destructors and Global Variables:

Destructors can interact with global variables, allowing them to modify or log global state changes when objects are destroyed.


<?php
$counter = 0;

class Counter {
    function __destruct() {
        global $counter;
        $counter++;
        echo "Counter incremented to $counter.\n";
    }
}

$obj1 = new Counter();
$obj2 = new Counter();
?>
    

Example Explanation:

This example demonstrates how a destructor can modify a global variable, incrementing a counter each time an object is destroyed.

Console Output:

Counter incremented to 1. Counter incremented to 2.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025