Fetches the metadata associated with an object key.
The examples focus on the operation itself, including the important distinction: offsetSet creates or updates the association.
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::offsetGet($object): mixed
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: mixed. 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];
echo $metadata->offsetGet($user)["score"];
Output from a successful local PHP 8.4 run:
2
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];
echo $metadata->offsetGet($user)["score"];
Output from a successful local PHP 8.4 run:
3
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];
echo $metadata->offsetGet($user)["score"];
Output from a successful local PHP 8.4 run:
4
Important Behavior and Edge Cases
A missing key throws an Error; test offsetExists first.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| WeakMap::offsetGet | Fetches the metadata associated with an object key. |
| Related API or alternative | offsetSet creates or updates the association. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | A missing key throws an Error; test offsetExists first. |
| Confusing it with a related API | offsetSet creates or updates the association. |
Key Takeaways
- Fetches the metadata associated with an object key.
- A missing key throws an Error; test offsetExists first.
- offsetSet creates or updates the association.
Use WeakMap::offsetGet when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.