Attach per-object cache or diagnostic state without adding fields to each class.
The examples focus on the operation itself, including the important distinction: Static arrays keyed by object IDs require explicit cleanup.
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
The map associates a derived discount with one object instance without adding a property to PriceLine.
<?php
final class PriceLine { public function __construct(public int $cents) {} }
$line = new PriceLine(125);
$discounts = new WeakMap();
$discounts[$line] = intdiv($line->cents, 10);
echo $line->cents - $discounts[$line];
Output from a successful local PHP 8.4 run:
113
Example 2: Checking Behavior
The map associates a derived discount with one object instance without adding a property to PriceLine.
<?php
final class PriceLine { public function __construct(public int $cents) {} }
$line = new PriceLine(250);
$discounts = new WeakMap();
$discounts[$line] = intdiv($line->cents, 10);
echo $line->cents - $discounts[$line];
Output from a successful local PHP 8.4 run:
225
Example 3: Practical Example
The map associates a derived discount with one object instance without adding a property to PriceLine.
<?php
final class PriceLine { public function __construct(public int $cents) {} }
$line = new PriceLine(399);
$discounts = new WeakMap();
$discounts[$line] = intdiv($line->cents, 10);
echo $line->cents - $discounts[$line];
Output from a successful local PHP 8.4 run:
360
Important Behavior and Edge Cases
Values should not accidentally capture their own object keys; that can retain objects through an indirect strong reference.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| Using WeakMap for Per-Object Metadata | Attach per-object cache or diagnostic state without adding fields to each class. |
| Related API or alternative | Static arrays keyed by object IDs require explicit cleanup. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | Values should not accidentally capture their own object keys; that can retain objects through an indirect strong reference. |
| Confusing it with a related API | Static arrays keyed by object IDs require explicit cleanup. |
Key Takeaways
- Attach per-object cache or diagnostic state without adding fields to each class.
- Values should not accidentally capture their own object keys; that can retain objects through an indirect strong reference.
- Static arrays keyed by object IDs require explicit cleanup.
Use Using WeakMap for Per-Object Metadata when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.