WeakMap in PHP 8
In PHP 8, WeakMap is a new built-in class that provides a way to associate arbitrary data with objects without preventing those objects from being garbage collected when they are no longer needed. WeakMap behaves similarly to a regular associative array (map), but it holds weak references to its keys, allowing those keys to be garbage collected if they are no longer referenced anywhere else in the code.
How WeakMap Works
Associating Data with Objects: You can use a WeakMap to associate data with objects. This can be useful in situations where you want to attach additional information to objects without modifying their internal structure or affecting their memory management.
Weak References: WeakMap holds weak references to its keys, meaning that if the object used as a key is no longer referenced anywhere else in the code, it can be garbage collected even if it's still present in the WeakMap.
Garbage Collection: When an object used as a key in a WeakMap is garbage collected, the corresponding entry in the WeakMap is automatically removed. This helps prevent memory leaks by ensuring that objects are only retained in the WeakMap as long as they are still needed elsewhere in the code.
Example Usage
<?php
$map = new WeakMap();
// Create an object
$obj = new stdClass();
// Associate data with the object
$map[$obj] = 'Associated Data';
// Check if the object is still present in the WeakMap
if (isset($map[$obj])) {
echo "Data associated with object: " . $map[$obj] . "\n";
} else {
echo "Object no longer referenced\n";
}
// Unset the reference to the object
unset($obj);
// Check if the object is still present in the WeakMap
if (isset($map[$obj])) {
echo "Data associated with object: " . $map[$obj] . "\n";
} else {
echo "Object no longer referenced\n";
}
In this example, the WeakMap associates data with an object $obj. After unsetting the reference to $obj, it is no longer referenced anywhere else in the code, so it can be garbage collected. As a result, the entry in the WeakMap is automatically removed.