How does the garbage collector work in PHP?

 In PHP, the Garbage Collector (GC) is responsible for automatically manages memory, freeing up resources that are no longer in use by your scripts, preventing memory leaks. PHP primarily uses reference counting, but it also has a cycle collector to deal with more complex scenarios like circular references.

Freeing objects that are no longer needed prevents memory leaks.

The GC uses a counting mechanism to determine the elements to drop. If no references point to a particular object (i.e., $counter = 0), then this object is eligible for cleanup.

1. Reference Counting

Every PHP variable (zval) holds a refcount—an internal counter that tracks how many symbols (variable names or properties) refer to it.

  • Every variable in PHP has a reference count.

  • When you assign a variable or pass it to a function, the reference count increases.

  • When the reference count drops to zero, PHP frees the memory.

Example:


$a = new stdClass(); // refcount = 1 $b = $a; // refcount = 2 unset($a); // refcount = 1 unset($b); // refcount = 0 → object is destroyed

2.  Circular References Problem


Reference counting alone can't detect circular references — when two or more objects reference each other, even if nothing else does.

Example:

$a = new stdClass();
$b = new stdClass();
$a->ref = $b;
$b->ref = $a;
unset($a);
unset($b);
// Objects still exist because of mutual references → memory leak!

3. Cycle Collector (Since PHP 5.3+)

To solve this, PHP introduced a cycle collector:

  • It periodically scans memory for circular references.

  • It finds groups of objects that reference each other but are otherwise unreachable.

  • It breaks these cycles and frees the memory.

4. Triggering and Controlling GC

You can manually interact with the GC using these functions:

gc_enable();       // Enable garbage collection (default is on)

gc_disable();      // Disable garbage collection

gc_collect_cycles(); // Force collection of cycles

gc_enabled();      // Check if GC is enabled


5. Performance Considerations

  • GC adds some overhead, but it’s essential for long-running scripts (e.g., daemons, workers).

  • For short scripts, reference counting alone is usually enough.

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...