Just to be clear, the value returned by a generator is not yielded while it is running, but is available afterwards through the getReturn() method.
One use for this could be to record the output of a generator so that it can be iterated over again without having to reconstruct and re-run the generator. (Indeed, one could write a generator that simply does exactly this for any given iterable.)
<?php
function generate_squares($n)
{
$record = [];
for($i = 0; $i <= $n; ++$i)
{
yield ($record[] = $i * $i);
}
return $record;
}
$squares = generate_squares(10);
foreach($squares as $s)
{
echo $s, ' ';
}
$recorded = $squares->getReturn();
echo "\nThat's [", join(', ', $recorded), "]";
?>
Recording keys as well would take a bit more work, as generators are free to repeat them but arrays aren't.