Removes the mapping for a specific object instance.
The examples focus on the operation itself, including the important distinction: offsetSet attaches metadata; offsetUnset detaches it.
What It Does
Use the examples below to observe the behavior on a small dataset before extending it to application code.
Syntax and Return Value
WeakMap::offsetUnset($object): void
The displayed signature describes the API or identifies any correction or optional dependency. When a parameter is optional, supply it only when the task requires it.
Parameters
- object: required.
Declared return type: void. Read the behavior notes for important cases such as empty collections and destructive iteration.
Example 1: Basic Use
The map tracks an object only while another strong reference keeps it alive; keys use identity rather than a name string.
<?php
$user = (object) ["name" => 'Ari'];
$other = (object) ["name" => "guest"];
$metadata = new WeakMap();
$metadata[$user] = ["score" => 2];
$metadata->offsetUnset($user);
echo count($metadata);
Output from a successful local PHP 8.4 run:
0
Example 2: Checking Behavior
The map tracks an object only while another strong reference keeps it alive; keys use identity rather than a name string.
<?php
$user = (object) ["name" => 'Bo'];
$other = (object) ["name" => "guest"];
$metadata = new WeakMap();
$metadata[$user] = ["score" => 3];
$metadata->offsetUnset($user);
echo count($metadata);
Output from a successful local PHP 8.4 run:
0
Example 3: Practical Example
The map tracks an object only while another strong reference keeps it alive; keys use identity rather than a name string.
<?php
$user = (object) ["name" => 'Cam'];
$other = (object) ["name" => "guest"];
$metadata = new WeakMap();
$metadata[$user] = ["score" => 4];
$metadata->offsetUnset($user);
echo count($metadata);
Output from a successful local PHP 8.4 run:
0
Important Behavior and Edge Cases
This does not destroy the object if references exist elsewhere.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| WeakMap::offsetUnset | Removes the mapping for a specific object instance. |
| Related API or alternative | offsetSet attaches metadata; offsetUnset detaches it. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | This does not destroy the object if references exist elsewhere. |
| Confusing it with a related API | offsetSet attaches metadata; offsetUnset detaches it. |
Key Takeaways
- Removes the mapping for a specific object instance.
- This does not destroy the object if references exist elsewhere.
- offsetSet attaches metadata; offsetUnset detaches it.
Use WeakMap::offsetUnset when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.