- next: documentation ( source)
- current: documentation ( source)
<?php
function makeGen(array $array = []): Generator
{
$item = current($array);
yield $item;
while($item = next($array)) {
yield $item;
}
}
class GeneratorIterator implements \Iterator
{
private $genMaker;
private $genArg;
private $current;
public function __construct(callable $genMaker, $arg)
{
$this->genMaker = $genMaker;
$this->genArg = $arg;
$this->current = $genMaker($arg);
}
public function current()
{
return $this->current->current();
}
public function key()
{
return $this->current->key();
}
public function rewind()
{
$this->current = call_user_func($this->genMaker, $this->genArg);
}
public function valid()
{
return $this->current->valid();
}
public function next()
{
$this->current->next();
}
}
$genIterator = new GeneratorIterator('makeGen', [1,2,3]);
foreach($genIterator as $key => $value) {
echo $key . ' -> ' . $value . "\n";
}
echo "\n";
foreach($genIterator as $key => $value) {
echo $key . ' -> ' . $value . "\n";
}