Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

WeakMap Allows Reference Assignment To A Missing Key

Taking a reference to a WeakMap offset with =& used to require the key to already be present in the map, otherwise PHP threw an Error saying the object was not contained in the WeakMap. In PHP 8.6, a reference assignment on a missing key first creates the entry, exactly like $array[$key] =& $ref does for a regular array, and then binds the reference to it.

PHP code

<?php

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

$ref =& $map[$obj];
$ref = 'value via reference';

var_dump($map[$obj]);

?>

Before

PHP Fatal error:  Uncaught Error: Object stdClass#2 not contained in WeakMap in /codes/weakMapReferenceAssign86.php:6
Stack trace:
#0 {main}
  thrown in /codes/weakMapReferenceAssign86.php on line 6

Fatal error: Uncaught Error: Object stdClass#2 not contained in WeakMap in /codes/weakMapReferenceAssign86.php:6
Stack trace:
#0 {main}
  thrown in /codes/weakMapReferenceAssign86.php on line 6

After

string(19) "value via reference" 

PHP version change

This behavior changed in 8.6.

See Also

Extension

© 2023-2026, Damien Seguy - Exakat