An interesting aspect, which worth to be discussed here, is yielding by reference. Every time we need to change a parameter such that it is reflected outside of the function, we have to pass this parameter by reference. To apply this to generators, we simply prepend an ampersand &
to the name of the generator and to the variable used in the iteration:
<?php
/**
* Yields by reference.
* @param int $from
*/
function &counter($from) {
while ($from > 0) {
yield $from;
}
}
foreach (counter(100) as &$value) {
$value--;
echo $value . '...';
}
// Output: 99...98...97...96...95...
The above example shows how changing the iterated values within the foreach
loop changes the $from
variable within the generator. This is because $from
is yielded by reference due to the ampersand before the generator name. Because of that, the $value
variable within the foreach
loop is a reference to the $from
variable within the generator function.