Assign Reference to New WeakMap Entry in PHP 8.6

Assign Reference to New WeakMap Entry in PHP 8.6

In PHP, a WeakMap stores data for objects. Objects are used as keys, and any value can be stored for them. When an object is no longer used anywhere else, its entry is removed from the map automatically. This makes it suitable for attaching data to objects without keeping them in memory longer than needed.

A value can also be assigned by reference. This worked only if the object was already in the map, so an entry had to be created first:

<?php

$user = new stdClass();
$map = new WeakMap();

$map[$user] = 0;

$visits = 0;
$map[$user] = &$visits;
$visits++;
$visits++;

echo $map[$user]; // 2

The $map[$user] = 0; line is a placeholder. Its only purpose is to put the object in the map, because without it the reference assignment on the next line failed.

Since PHP 8.6, a reference can be assigned even when the object is not in the map yet:

<?php

$user = new stdClass();
$map = new WeakMap();

$visits = 0;
$map[$user] = &$visits;
$visits++;
$visits++;

echo $map[$user];

Before PHP 8.6:

Fatal error: Uncaught Error: Object stdClass#1 not contained in WeakMap in main.php:7

Since PHP 8.6:

2

The map holds a reference, not a copy. The $visits variable is incremented twice and the map reports 2, even though nothing was written to the map after the assignment. Code which changes the value does not need access to the map.

Storing a reference does not change how the map works. When the object is no longer used anywhere else, its entry is removed as before.

Leave a Comment

Cancel reply

Your email address will not be published.