3v4l.org

run code in 300+ PHP versions simultaneously
<?php $records = [ 't' => new WeakMap(), ]; class X { public array $id; public function __destruct() { var_dump('Cleaning up: ' . json_encode($this->id)); } } // Treat this as usages external to Records itself. $external = []; (function () use (&$records, &$external) { foreach (range(0, 3) as $i) { $x = new X(); $x->id = [$i]; $records['t'][$x] = WeakReference::create($x); $external[] = $x; } })(); $finder = function (array $find) use (&$records) { foreach ($records['t'] as $object => $ref) { if ($object->id == $find) { return $object; } } }; var_dump('Found object:', $finder([2])); var_dump('Found object:', $finder([99])); var_dump(count($records['t'])); var_dump('Removing external 2 (should auto-destruct)'); unset($external[2]); var_dump(count($records['t'])); var_dump('Exiting...');
Output for 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
string(13) "Found object:" object(X)#7 (1) { ["id"]=> array(1) { [0]=> int(2) } } string(13) "Found object:" NULL int(4) string(42) "Removing external 2 (should auto-destruct)" string(16) "Cleaning up: [2]" int(3) string(10) "Exiting..." string(16) "Cleaning up: [0]" string(16) "Cleaning up: [1]" string(16) "Cleaning up: [3]"

preferences:
51.06 ms | 407 KiB | 5 Q