WeakMap stores object-associated metadata without keeping its object keys alive.
The examples focus on the operation itself, including the important distinction: SplObjectStorage strongly retains object keys until detached.
What It Does
Use the examples below to observe the behavior on a small dataset before extending it to application code.
Before You Start
Read the input requirements before applying this pattern to production data.
Example 1: Basic Use
After releasing the only strong object reference, the WeakMap entry disappears; avoid values that themselves hold their own key.
<?php
$item = (object) ["id" => 3];
$states = new WeakMap();
$states[$item] = ["visited" => true, "source" => 'new'];
echo $states[$item]["source"];
unset($item);
gc_collect_cycles();
echo count($states);
Output from a successful local PHP 8.4 run:
new0
Example 2: Checking Behavior
After releasing the only strong object reference, the WeakMap entry disappears; avoid values that themselves hold their own key.
<?php
$item = (object) ["id" => 8];
$states = new WeakMap();
$states[$item] = ["visited" => true, "source" => 'ready'];
echo $states[$item]["source"];
unset($item);
gc_collect_cycles();
echo count($states);
Output from a successful local PHP 8.4 run:
ready0
Example 3: Practical Example
After releasing the only strong object reference, the WeakMap entry disappears; avoid values that themselves hold their own key.
<?php
$item = (object) ["id" => 21];
$states = new WeakMap();
$states[$item] = ["visited" => true, "source" => 'done'];
echo $states[$item]["source"];
unset($item);
gc_collect_cycles();
echo count($states);
Output from a successful local PHP 8.4 run:
done0
Important Behavior and Edge Cases
The WeakMap itself must stay alive, and a metadata value that strongly references its own key may undermine weak-key benefits.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| PHP WeakMap: Avoiding Object Metadata Memory Leaks | WeakMap stores object-associated metadata without keeping its object keys alive. |
| Related API or alternative | SplObjectStorage strongly retains object keys until detached. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | The WeakMap itself must stay alive, and a metadata value that strongly references its own key may undermine weak-key benefits. |
| Confusing it with a related API | SplObjectStorage strongly retains object keys until detached. |
Key Takeaways
- WeakMap stores object-associated metadata without keeping its object keys alive.
- The WeakMap itself must stay alive, and a metadata value that strongly references its own key may undermine weak-key benefits.
- SplObjectStorage strongly retains object keys until detached.
Use PHP WeakMap: Avoiding Object Metadata Memory Leaks when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.