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));

preferences:
42.49 ms | 1425 KiB | 5 Q