TExcelTAD
Home › PHP › PHP Destructor

PHP Destructor

A destructor is the opposite of a constructor: PHP calls it automatically when an object is about to be destroyed. In PHP the destructor method is named __destruct and takes no parameters.

Destructors are useful for cleanup — closing a file handle, releasing a lock, writing a final log line — in situations where you want the cleanup to happen no matter how the object stops being used.

When does an object get destroyed?

PHP uses reference counting. Every object keeps track of how many variables (and arrays, properties, …) point to it. As soon as that count drops to zero, the object is destroyed and its destructor runs. That happens when:

  • you unset() the last variable that refers to it,
  • you assign something else to that variable (for example null),
  • the variable goes out of scope, such as a local variable at the end of a function,
  • the script ends (all remaining objects are destroyed).
php · try it yourself
<?php
class Resource {
    public function __construct(private string $name) {
        echo "open {$this->name}\n";
    }

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

$a = new Resource('A');
$b = new Resource('B');

unset($a);        // last reference to A is gone
echo "after unset\n";

$b = null;        // same effect for B
echo "done\n";
open A
open B
close A
after unset
close B
done

The destructor ran immediately at unset($a) and at $b = null, not at the end of the script.

Scope and shared references

A local object is destroyed when its function returns — unless something else still holds a reference to it:

php · try it yourself
<?php
class Tracker {
    public function __construct(public string $id) {}
    public function __destruct() { echo "destroy {$this->id}\n"; }
}

function work(): void {
    $temp = new Tracker('temp');
    echo "working\n";
}   // $temp goes out of scope here

work();
echo "back in main\n";

$first = new Tracker('shared');
$second = $first;     // two references now
unset($first);
echo "first unset, still alive\n";
unset($second);
echo "end\n";
working
destroy temp
back in main
first unset, still alive
destroy shared
end

unset($first) did not destroy the object, because $second still referred to it. Only after the second reference disappeared did the destructor run.

Destruction at the end of the script

Objects that are still alive when the script finishes are destroyed during shutdown, and their destructors run then. The exact order of shutdown destruction is an implementation detail, so do not write code that depends on it. If the order matters, destroy objects explicitly:

php · try it yourself
<?php
class Step {
    public function __construct(private int $n) {}
    public function __destruct() { echo "cleanup step {$this->n}\n"; }
}

$steps = [new Step(1), new Step(2), new Step(3)];

// Remove them in reverse order on purpose
while ($steps) {
    array_pop($steps);
}
echo "all steps cleaned up\n";
cleanup step 3
cleanup step 2
cleanup step 1
all steps cleaned up

array_pop() removes the last element of the array, which was the only reference to that object, so its destructor fires right away.

A practical example: a timed section

A destructor can write a closing message for a block of work, like a tiny "scope guard":

php · try it yourself
<?php
class Section {
    private static int $depth = 0;

    public function __construct(private string $title) {
        echo str_repeat('  ', self::$depth) . "begin {$title}\n";
        self::$depth++;
    }

    public function __destruct() {
        self::$depth--;
        echo str_repeat('  ', self::$depth) . "end {$this->title}\n";
    }
}

function importData(): void {
    $s = new Section('import');
    $inner = new Section('validate');
    unset($inner);
    echo "    ...saving rows\n";
}

importData();
begin import
  begin validate
  end validate
    ...saving rows
end import

Rules and caveats

Rule Detail
Name __destruct(), no parameters
Return value Ignored
Parent destructor Not called automatically — call parent::__destruct() yourself if needed
Exceptions Avoid throwing from a destructor, especially during shutdown
Circular references Objects that refer to each other are freed later by the cycle collector, so their destructors may run late

Note: Most of the time you do not need a destructor at all. PHP automatically closes files, database connections and frees memory when objects disappear. Use __destruct only for cleanup PHP cannot know about.

Tip: In long-running scripts (queue workers, daemons), relying on destructors for important cleanup is risky. Prefer an explicit close() method or a try/finally block.

Test yourself

When is __destruct called for an object stored only in $x?

  1. Only when the script ends
  2. When unset($x) removes the last reference
  3. Never automatically
  4. Every time a method is called

$a = new Obj(); $b = $a; unset($a); — is the destructor called?

  1. Yes, immediately
  2. No, because $b still refers to the object
  3. Yes, but only for $a's copy
  4. It throws an error

Does a child class destructor call the parent's destructor automatically?

  1. Yes, always
  2. No, you must call parent::__destruct() explicitly
  3. Only if the parent is abstract
  4. Only at script end