3v4l.org

run code in 300+ PHP versions simultaneously
<?php class RewindableGenerator implements Iterator { private $rewound; private $iteratorConstructor; private $iterator; function __construct(callable $iteratorConstructor){ $this->iteratorConstructor = $iteratorConstructor; $this->rewind(); } function rewind(){ if(!$this->rewound){ $this->iterator = ($this->iteratorConstructor)(); $this->rewound = true; } } function next(){ $this->iterator->next(); $this->rewound = false; } function valid(){ return $this->iterator->valid(); } function key(){ return $this->iterator->key(); } function current(){ return $this->iterator->current(); } } function test(){ yield 0; yield 1; yield 2; yield 3; yield 4; } function baz(){ return new RewindableGenerator('test'); } $gen = baz(); echo $gen->current() . " 0\n"; $gen->next(); echo $gen->current() . " 1\n"; $gen->next(); echo $gen->current() . " 2\n"; $gen->next(); echo $gen->current() . " 3\n"; echo "rewind\n"; $gen->rewind(); echo $gen->current() . " 0\n"; $gen->next(); echo $gen->current() . " 1\n"; $gen->next(); echo $gen->current() . " 2\n";
Output for 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
Deprecated: Return type of RewindableGenerator::current() should either be compatible with Iterator::current(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/YS6Ze on line 34 Deprecated: Return type of RewindableGenerator::next() should either be compatible with Iterator::next(): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/YS6Ze on line 21 Deprecated: Return type of RewindableGenerator::key() should either be compatible with Iterator::key(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/YS6Ze on line 30 Deprecated: Return type of RewindableGenerator::valid() should either be compatible with Iterator::valid(): bool, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/YS6Ze on line 26 Deprecated: Return type of RewindableGenerator::rewind() should either be compatible with Iterator::rewind(): void, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /in/YS6Ze on line 14 0 0 1 1 2 2 3 3 rewind 0 0 1 1 2 2
Output for 7.0.0 - 7.0.20, 7.1.0 - 7.1.20, 7.2.0 - 7.2.33, 7.3.16 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30
0 0 1 1 2 2 3 3 rewind 0 0 1 1 2 2
Output for 5.5.0 - 5.5.35, 5.6.0 - 5.6.28
Parse error: syntax error, unexpected '(' in /in/YS6Ze on line 16
Process exited with code 255.

preferences:
182.55 ms | 402 KiB | 214 Q