3v4l.org

run code in 300+ PHP versions simultaneously
<?php class MemoryCache { protected $data = []; public function set($key, $value) { $this->data[$key] = $value; } public function get($key) { return $this->data[$key] ?? NULL; } } class InternalReferenceCycleVoodooMemoryCacheWrapper { protected $memoryCache; protected $cycle; public function __construct(MemoryCache $memoryCache) { $this->memoryCache = $memoryCache; $this->cycle = $this; } public function unwrap() { return $this->memoryCache; } } class GarbageCollectableMemoryCacheDecorator { protected $memoryCacheWrapperWeakref; protected function createWrapper(): InternalReferenceCycleVoodooMemoryCacheWrapper { return new InternalReferenceCycleVoodooMemoryCacheWrapper(new MemoryCache()); } protected function initWeakref(): WeakReference { return $this->memoryCacheWrapperWeakref = WeakReference::create($this->createWrapper()); } protected function getMemoryCache() { $weakref = $this->memoryCacheWrapperWeakref ?? $this->initWeakref(); $wrapper = $weakref->get() ?? $this->initWeakref()->get(); return $wrapper->unwrap(); } public function set($key, $value) { $this->getMemoryCache()->set($key, $value); } public function get($key) { return $this->getMemoryCache()->get($key); } } $mc = new GarbageCollectableMemoryCacheDecorator(); $mc->set('foo', 'bar'); printf("Data value after set: %s\n", print_r($mc->get('foo'), 1)); gc_collect_cycles(); printf("Data value after GC: %s\n", print_r($mc->get('foo'), 1)); $mc->set('foo', 'baz'); printf("Data value after set: %s\n", print_r($mc->get('foo'), 1)); gc_collect_cycles(); printf("Data value after GC: %s\n", print_r($mc->get('foo'), 1));
Output for 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.4, 8.3.6 - 8.3.7
Data value after set: bar Data value after GC: Data value after set: baz Data value after GC:
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 Data value after set: bar Data value after GC: Data value after set: baz Data value after GC:
Output for 7.3.0 - 7.3.33
Fatal error: Uncaught Error: Class 'WeakReference' not found in /in/MG8tb:43 Stack trace: #0 /in/MG8tb(47): GarbageCollectableMemoryCacheDecorator->initWeakref() #1 /in/MG8tb(53): GarbageCollectableMemoryCacheDecorator->getMemoryCache() #2 /in/MG8tb(63): GarbageCollectableMemoryCacheDecorator->set('foo', 'bar') #3 {main} thrown in /in/MG8tb on line 43
Process exited with code 255.

preferences:
109.03 ms | 402 KiB | 158 Q