Content · Web Development · PHP

PHP WeakMap Explained with a Practical Example

WeakMap stores metadata keyed by objects without extending their lifetime solely through the map. Do not depend on exact garbage-collection timing; keys vanish when no strong references.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

WeakMap stores metadata keyed by objects without extending their lifetime solely through the map.

What It Does


WeakMap stores metadata keyed by objects without extending their lifetime solely through the map. 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


Apply the technique to a small practical task.

<?php
$item = new stdClass(); $reference = WeakReference::create($item);
var_dump($reference->get() === $item);
unset($item); gc_collect_cycles(); var_dump($reference->get());

Important Behavior and Edge Cases


Do not depend on exact garbage-collection timing; keys vanish when no strong references remain.

Comparison with Related Functions or Approaches


OptionWhat it means in practice
WeakMap Explained with a Practical ExampleWeakMap stores metadata keyed by objects without extending their lifetime solely through the map.
Related approachSplObjectStorage retains object keys strongly instead of weakly.

Common Beginner Mistakes


MistakeCorrect approach
Ignoring the important boundary for WeakMap Explained with a Practical ExampleDo not depend on exact garbage-collection timing; keys vanish when no strong references remain.
Assuming a related mechanism has the same behaviorSplObjectStorage retains object keys strongly instead of weakly.

Key Takeaways


  • WeakMap stores metadata keyed by objects without extending their lifetime solely through the map.
  • Do not depend on exact garbage-collection timing; keys vanish when no strong references remain.
  • SplObjectStorage retains object keys strongly instead of weakly.

Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.

Share this resourceSend this page to someone who may find it useful.