WeakReference and WeakMap observe or annotate objects without keeping them alive only through the weak reference.
What It Does
WeakReference and WeakMap observe or annotate objects without keeping them alive only through the weak reference. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.0 or later and object instances as WeakMap keys.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Start with the smallest meaningful working case.
<?php
$metadata = new WeakMap(); $object = new stdClass(); $metadata[$object] = ['hits' => 1];
echo $metadata[$object]['hits'];
Example 2: Another Case
Examine the edge case and the observable result.
<?php
$map = new WeakMap(); $key = new stdClass(); $map[$key] = 'temporary';
unset($key); gc_collect_cycles(); echo count($map);
Practical Example: Putting It to Use
A WeakReference observes collection without acting as a strong object owner.
<?php
$object = new stdClass(); $ref = WeakReference::create($object);
echo $ref->get() !== null ? 'Present ' : 'Missing ';
unset($object); gc_collect_cycles();
echo $ref->get() === null ? 'Collected' : 'Referenced';
Important Behavior and Edge Cases
Objects may be collected once no strong references remain; do not depend on collection timing.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Weak References and WeakMap | WeakReference and WeakMap observe or annotate objects without keeping them alive only through the weak reference. |
| Related approach | Use SplObjectStorage when you intentionally need strong ownership of keys. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Weak References and WeakMap | Objects may be collected once no strong references remain; do not depend on collection timing. |
| Assuming a related mechanism has the same behavior | Use SplObjectStorage when you intentionally need strong ownership of keys. |
Key Takeaways
- WeakReference and WeakMap observe or annotate objects without keeping them alive only through the weak reference.
- Objects may be collected once no strong references remain; do not depend on collection timing.
- Use SplObjectStorage when you intentionally need strong ownership of keys.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.