PHP Destructor

A destructor is a special method that PHP runs automatically just before an object is destroyed, giving you a chance to release any resources it was holding.

What a destructor does

The counterpart to the constructor is the destructor, a method named __destruct. PHP calls it automatically when an object is no longer needed, which happens either when there are no more references to it or when the script finishes running. You never call a destructor directly; the engine decides when it is time.

A simple destructor

<?php
class Logger
{
    public function __construct(public string $name)
    {
        echo "Logger {$this->name} started.\n";
    }

    public function __destruct()
    {
        echo "Logger {$this->name} shutting down.\n";
    }
}

$log = new Logger("app");
// When the script ends, PHP calls __destruct automatically:
// Logger app started.
// Logger app shutting down.
?>

When is the destructor called?

PHP uses reference counting to track how many variables point to an object. As soon as that count drops to zero, the object becomes eligible for cleanup and its destructor runs. You can trigger this deliberately by unsetting the last variable that references the object, or by reassigning it to something else.

  • When the last reference to an object is removed with unset().
  • When a variable holding the object is reassigned to a different value.
  • When a function ends and its local object variables go out of scope.
  • When the script finishes and PHP cleans up everything that remains.

Forcing early cleanup with unset

<?php
class FileWriter
{
    public function __construct(public string $path)
    {
        echo "Opened {$this->path}\n";
    }

    public function __destruct()
    {
        echo "Closed {$this->path}\n";
    }
}

$writer = new FileWriter("report.txt");
unset($writer);        // Closed report.txt (runs here)
echo "After unset\n";   // After unset
?>

Common uses for a destructor

Destructors are most useful for tidying up external resources that PHP will not automatically reclaim, such as closing a file handle, ending a network connection, or writing out a final log entry. For plain data objects you usually do not need a destructor at all, since PHP handles freeing memory on its own.

MethodNameRuns when
Constructor__constructImmediately after the object is created
Destructor__destructJust before the object is destroyed
Note: Do not rely on a destructor running at an exact moment. Its timing depends on when references are released and on PHP's garbage collection, so avoid putting time-critical logic inside __destruct.