What are Weak Maps in PHP?

Weak Maps in PHP are a memory-efficient data structure that creates weak references to objects, allowing automatic garbage collection when objects are no longer needed elsewhere in your code. Introduced in PHP 8.0, weak maps help prevent memory leaks by automatically removing entries when their object keys are destroyed.

How Weak Maps Work

A WeakMap stores key-value pairs where the keys must be objects and are weakly referenced. Unlike regular arrays or maps, if an object used as a key is destroyed (no other references exist), the corresponding entry in the WeakMap is automatically removed during garbage collection −

Regular Map Holds strong references WeakMap Holds weak references Object destroyed ? Entry remains Object destroyed ? Entry auto-removed Memory Leak No Memory Leak

Example

Here's a practical example showing how WeakMap automatically cleans up entries when objects are destroyed −

<?php
class CacheExample {
    public WeakMap $cache;
    
    public function __construct() {
        $this->cache = new WeakMap();
    }
    
    public function getCachedData(object $obj) {
        return $this->cache[$obj] ??= $this->computeExpensiveOperation($obj);
    }
    
    public function computeExpensiveOperation(object $obj) {
        echo "Computing expensive operation...<br>";
        return "Cached result for " . get_class($obj);
    }
}

// Create objects
$obj1 = new stdClass();
$obj2 = new stdClass();
$cache = new CacheExample();

// Cache data for both objects
echo $cache->getCachedData($obj1) . "<br>";
echo $cache->getCachedData($obj2) . "<br>";
echo "Cache size: " . count($cache->cache) . "<br>";

// Destroy one object
unset($obj1);
gc_collect_cycles(); // Force garbage collection

echo "Cache size after destroying obj1: " . count($cache->cache) . "<br>";

// Second call uses cached data
echo $cache->getCachedData($obj2) . "<br>";
?>

The output demonstrates automatic cleanup when objects are destroyed −

Computing expensive operation...
Cached result for stdClass
Computing expensive operation...
Cached result for stdClass
Cache size: 2
Cache size after destroying obj1: 1
Cached result for stdClass

Key Benefits

Feature Regular Array/Map WeakMap
Memory Management Manual cleanup required Automatic cleanup
Reference Type Strong references Weak references
Memory Leaks Possible if not cleaned Prevented automatically

Conclusion

WeakMaps in PHP provide automatic memory management by using weak references to object keys. They're ideal for caching scenarios where you want to associate data with objects without preventing garbage collection, effectively eliminating memory leaks in long-running applications.

Updated on: 2026-03-15T09:43:39+05:30

508 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements