Memory Management and Garbage Collection
See how zvals, refcounting and the GC work.
How PHP Manages Memory
PHP values live in zvals, managed mostly by reference counting, with a cycle collector to catch what refcounting can't. Understanding this explains memory leaks in long-running workers, the cost of copies, and when gc_collect_cycles() matters.
The zval
A zval is the container for any PHP value: a type tag plus a union of value storage. Scalars (int, float, bool) are stored by value inside the zval and are NOT refcounted. Complex types (string, array, object) point to a refcounted structure on the heap.
<?php
// debug_zval_refcount-style inspection via gc + count
$arr = [1, 2, 3];
$copy = $arr; // refcount of the array bumps, no data copy yet (CoW)
// Modifying triggers copy-on-write separation
$copy[] = 4;
var_dump($arr); // still [1,2,3]
var_dump($copy); // [1,2,3,4]
?>All lessons in this course
- How the Zend Engine Works
- Memory Management and Garbage Collection
- OPcache and JIT Compilation
- Writing a Basic PHP Extension in C