PHP Destructors
A destructor — __destruct — runs when the last reference to an instance disappears. Use it for cleanup; never for business logic.
Shape
PHP
class Logger {
private $handle;
public function __construct(string $path) {
$this->handle = fopen($path, 'a');
}
public function __destruct() {
if ($this->handle) {
fclose($this->handle);
}
}
}
When it fires
| Event | Destructor runs? |
|---|---|
| Last reference unset / overwritten | Yes, right then. |
| Script ends normally | Yes, in (mostly) creation order. |
Fatal error / die() | Maybe — don't rely on it. |
| Object inside a circular reference | Yes, but only after the GC sweep. |
Prefer explicit cleanup
In long-lived PHP processes (CLI workers, Swoole, ReactPHP) you often can't predict when the destructor fires. For deterministic cleanup expose a method and call it:
PHP
class FileWriter {
private $handle;
public function __construct(string $path) { $this->handle = fopen($path, 'w'); }
public function close(): void {
if ($this->handle) { fclose($this->handle); $this->handle = null; }
}
public function __destruct() { $this->close(); }
}
$w = new FileWriter('out.txt');
// … use $w …
$w->close(); // explicit, predictable
Tip: Avoid heavy work in destructors. Throwing an exception from one is also a bad idea — PHP will warn and the rest of shutdown gets messy.
Example
Example
<?php
class Logger {
public function __construct() { echo "open\n"; }
public function __destruct() { echo "close\n"; }
}
new Logger(); // logged open and close immediately
Try it Yourself »
Exercise
Destructor method name.
public function
() { fclose($this->h); }
Double-underscore + destruct.
Discussion
Loading…