Use WeakMap to keep temporary metadata keyed by specific object identities.
The examples focus on the operation itself, including the important distinction: SplObjectStorage holds keys strongly and may cause retention.
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
Temporary validation metadata lives outside the object and does not make the map retain the object indefinitely.
<?php
$account = (object) ["name" => 'A'];
$map = new WeakMap();
$map[$account] = ["validated" => true];
if (isset($map[$account])) { echo $account->name . ":" . (int) $map[$account]["validated"]; }
Output from a successful local PHP 8.4 run:
A:1
Example 2: Checking Behavior
Temporary validation metadata lives outside the object and does not make the map retain the object indefinitely.
<?php
$account = (object) ["name" => 'B'];
$map = new WeakMap();
$map[$account] = ["validated" => true];
if (isset($map[$account])) { echo $account->name . ":" . (int) $map[$account]["validated"]; }
Output from a successful local PHP 8.4 run:
B:1
Example 3: Practical Example
Temporary validation metadata lives outside the object and does not make the map retain the object indefinitely.
<?php
$account = (object) ["name" => 'C'];
$map = new WeakMap();
$map[$account] = ["validated" => true];
if (isset($map[$account])) { echo $account->name . ":" . (int) $map[$account]["validated"]; }
Output from a successful local PHP 8.4 run:
C:1
Important Behavior and Edge Cases
Always retain a strong reference to objects you need later, because weak keys disappear on collection.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| Using WeakMap for Object Metadata | Use WeakMap to keep temporary metadata keyed by specific object identities. |
| Related API or alternative | SplObjectStorage holds keys strongly and may cause retention. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | Always retain a strong reference to objects you need later, because weak keys disappear on collection. |
| Confusing it with a related API | SplObjectStorage holds keys strongly and may cause retention. |
Key Takeaways
- Use WeakMap to keep temporary metadata keyed by specific object identities.
- Always retain a strong reference to objects you need later, because weak keys disappear on collection.
- SplObjectStorage holds keys strongly and may cause retention.
Use Using WeakMap for Object Metadata when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.