I have a method that takes a generator plus some additional parameters and gives a new generator:
function merge(\Generator $carry, array $additional) { foreach ( $carry as $item ) { yield $item; } foreach ( $additional as $item ) { yield $item; } }
A typical usage example for this function is similar to this:
function source() { for ( $i = 0; $i < 3; $i++ ) { yield $i; } } foreach ( merge(source(), [4, 5]) as $item ) { var_dump($item); }
But the problem is that sometimes I need to pass an empty source to the merge method. Ideally, I would like to do something like this:
merge(\Generator::getEmpty(), [4, 5]);
That is exactly what I would do in C # (there is the IEnumerable<T>.Empty ). But I do not see the empty generator in the manual .
I managed to get around this (for now) with this function:
function sourceEmpty() { if ( false ) { yield; } }
And it works. The code:
foreach ( merge(sourceEmpty(), [4, 5]) as $item ) { var_dump($item); }
correctly displays:
int(4) int(5)
But this is obviously not an ideal solution. What would be the correct way to pass an empty generator to the merge method?
source share