3v4l.org

run code in 300+ PHP versions simultaneously
<?php class IteratorWithFilter { public $generator; public function __construct(array $data) { $this->generator = new \ArrayIterator($data); } public function filter() { $weakRef = WeakReference::create($this); $this->generator = new CallbackFilterIterator($this->generator, static function(array $row) use ($weakRef) { $filterObj = $weakRef->get(); return $filterObj->matchRow($row); }); $this->generator->filterObj = $this; // this assigment will link the objects exactly the same as if // bound function is passed directly, thus the WeakReference // will always be valid/nonGCed return $this; } public function matchRow(array $row) { return $row[0] === 'b'; } } function createIterator() { $iter = new IteratorWithFilter([['a'], ['b']]); return $iter->filter(); } for ($i = 0; $i < 10 * 1000; $i++) { $generator = createIterator()->generator; iterator_to_array($generator); // must success and always return ['b'] if (($i % 10) === 0) { gc_collect_cycles(); } if (($i % 1000) === 0) { echo round(memory_get_usage() / (1024 * 1024), 3) . " MiB\n"; } }
Output for 7.4.2 - 7.4.10
0.378 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB
Output for 7.4.0 - 7.4.1
0.377 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB 0.398 MiB
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.22
Fatal error: Uncaught Error: Class 'WeakReference' not found in /in/U3h2Q:14 Stack trace: #0 /in/U3h2Q(33): IteratorWithFilter->filter() #1 /in/U3h2Q(37): createIterator() #2 {main} thrown in /in/U3h2Q on line 14
Process exited with code 255.

preferences:
88.19 ms | 402 KiB | 73 Q