(PHP 5 >= 5.5.0, PHP 7, PHP 8)
Generator::rewind — Execute the generator up to and including the first yield
Executes the generator up to and including the first yield.
If the generator is already at the first yield,
no action will be taken.
If the generator has ever advanced beyond a yield expression,
this method will throw an Exception.
Note:
This is the first method called when starting a
foreachloop. It will not be executed afterforeachloops.
This function has no parameters.
No value is returned.
Example #1 Generator::rewind() example
<?php
function generator(): Generator
{
echo "I'm a generator!\n";
for ($i = 1; $i <= 3; $i++) {
yield $i;
}
}
// Initialize the generator
$generator = generator();
// Rewind the generator to the beginning of the first yield expression,
// if it's not already there
$generator->rewind(); // I'm a generator!
// Nothing happens here; the generator is already rewound
$generator->rewind(); // No output (NULL)
// This rewinds the generator to the first yield expression,
// if it's not already there, and iterates over the generator
foreach ($generator as $value) {
// After yielding the first value, the generator remains at
// the first yield expression until it resumes execution and advances to the next yield
echo $value, PHP_EOL; // 1
break;
}
// Resume and rewind again. No error occurs because the generator has not advanced beyond the first yield
$generator->rewind();
echo $generator->current(), PHP_EOL; // 1
// No error occurs, the generator is still at the first yield
$generator->rewind();
// This advances the generator to the second yield expression
$generator->next();
try {
// This will throw an Exception,
// because the generator has already advanced to the second yield
$generator->rewind(); // Fatal error: Uncaught Exception: Cannot rewind a generator that was already run
} catch (Exception $e) {
echo $e->getMessage();
}
?>The above example will output:
I'm a generator! 1 1 Cannot rewind a generator that was already run