<?php class WrappingIterator implements \Iterator { private $index; private $iterator; public function __construct(int $index, Traversable $traversable) { printf('Creating %s %d' . PHP_EOL, static::class, $index); $this->index = $index; $this->iterator = $this->wrapTraversable($traversable); } public function __destruct() { printf('Destroying %s %d' . PHP_EOL, static::class, $this->index); } protected function destroyWrappedIterator() { $this->iterator = null; } public function current() { return $this->iterator->current(); } public function next() { $this->iterator->next(); } public function key() { return $this->iterator->key(); } public function valid() { return $this->iterator->valid(); } public function rewind() { $this->iterator->rewind(); } private function wrapTraversable(Traversable $traversable) { foreach ($traversable as $key => $value) { yield $key => $value; } } } class DestroyingIterator extends WrappingIterator { public function __destruct() { parent::__destruct(); $this->destroyWrappedIterator(); } } class WrappedIterator extends ArrayIterator { public function __construct(int $index) { parent::__construct([1, 2, 3, 4]); $this->index = $index; } public function __destruct() { printf('Destroying WrappedIterator %d' . PHP_EOL, $this->index); } } function testIterator(string $class, int $limit = 20) { printf('Starting run with class "%s" and limit "%d"' . PHP_EOL, $class, $limit); gc_enable(); gc_collect_cycles(); for ($i = 1; $i <= $limit; $i++) { $iterator = new $class($i, new WrappedIterator($i)); $iterator->current(); if ($i % 5 === 0) { gc_collect_cycles(); } } gc_collect_cycles(); echo 'Done', PHP_EOL; } testIterator(WrappingIterator::class); testIterator(DestroyingIterator::class);
You have javascript disabled. You will not be able to edit any code.
This script was stopped while abusing our resources