How PHP’s Garbage Collector Actually Works

PHP handles memory management automatically via reference counting plus a cycle-collecting garbage collector, but understanding roughly how it works helps you diagnose the occasional memory leak in a long-running script.

echo memory_get_usage() . " bytes\n";
echo memory_get_peak_usage() . " bytes\n";

// Reference counting handles most cleanup automatically
$a = new stdClass();
unset($a); // refcount hits 0, memory freed immediately

// Circular references need the cycle collector
class Node {
    public ?Node $next = null;
}
$n1 = new Node();
$n2 = new Node();
$n1->next = $n2;
$n2->next = $n1; // circular reference

unset($n1, $n2);
gc_collect_cycles(); // manually trigger cycle collection if needed

In practice, memory leaks in PHP web requests are rare because each request starts with a clean slate — the more common issue is long-running CLI scripts (workers, queue processors) that accumulate objects in a loop without ever letting go of references.