🐘 PHP Advanced

What is PHP's garbage collection mechanism?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

Answer

PHP uses reference counting as its primary memory management strategy — every variable has a reference count, and when it drops to zero, the memory is immediately freed. This works well for simple cases but fails with circular references (object A references B, B references A — both have refcount > 0 even when unreachable). To handle this, PHP 5.3+ added a cycle collector that periodically identifies circular reference cycles and frees them. The cycle collector runs when the root buffer exceeds 10,000 possible roots (gc_collect_cycles() can trigger it manually). PHP 8.0 improved GC with better detection. Set gc_enable() / gc_disable() to control it. For long-running scripts (daemons, queue workers), GC management is especially important to prevent memory exhaustion.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex PHP answers easy to follow.