CKTIS / PHP
__destruct
The parameterless `__destruct` can release resources when the object has no surviving references or during shutdown.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
public function __destruct() { /* cleanup */ }The parameterless __destruct can release resources when the object has no surviving references or during shutdown. Removing one variable does not finalize an object still held by another. Cycles can delay collection and shutdown ordering is unsuitable for dependencies between objects. If a child overrides the destructor it must explicitly call the parent destructor to run that cleanup.
class Tracked {
public static array $events = [];
public function __destruct() { self::$events[] = "released"; }
}
$a = new Tracked(); $b = $a;
unset($a);
echo json_encode(Tracked::$events), PHP_EOL;
unset($b);
echo json_encode(Tracked::$events);
[]
["released"]
Examples
<?php
class Tracked {
public static array $events = [];
public function __destruct() { self::$events[] = "released"; }
}
$a = new Tracked(); $b = $a;
unset($a);
echo json_encode(Tracked::$events), PHP_EOL;
unset($b);
echo json_encode(Tracked::$events);
Result
[] ["released"]