3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Item { private $key; private $expirations; public function __construct($key, ArrayObject $expirations) { $this->key = $key; $this->expirations = $expirations; } public function __destruct() { if (isset($this->expirations[$this->key])) { unset($this->expirations[$this->key]); } } public function getKey() { return $this->key; } public function setExpiration($expiration) { $this->expirations[$this->key] = $expiration; } } class Pool { private $expirations; public function __construct() { $this->expirations = new ArrayObject(); } public function getItem($key) { return new Item($key, $this->expirations); } public function save(Item $item) { $key = $item->getKey(); if (isset($this->expirations[$key])) { echo 'Item ' . $key . ' expires at: ' . $this->expirations[$key] . PHP_EOL; } else { echo 'Item ' . $key . ' expiry not set' . PHP_EOL; } } } // Test it works $pool = new Pool(); $foo = $pool->getItem('foo'); $bar = $pool->getItem('bar'); $foo->setExpiration(100); $pool->save($foo); // Item foo expires at 100 $pool->save($bar); // Item bar expiry not set // Check for protection against memory leak $foo2 = clone $foo; unset($foo); $pool->save($foo2); // Item foo expiry not set
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
Item foo expires at: 100 Item bar expiry not set Item foo expiry not set

preferences:
169.88 ms | 404 KiB | 329 Q