Recursive Generator¶
<?php
function foo() {
static $f = 0;
yield ++$f;
yield from goo();
}
function goo() {
static $g = 'a';
yield ++$g;
yield from foo();
}
foreach (foo() as $foo) {
print $foo.PHP_EOL;
}
?>
Generators in PHP, when using the yield keyword, can become recursive through the use of the yield from construct. This allows a generator to delegate part of its iteration to another generator, creating a chain of generators. However, this recursive behavior is only effective when the generator is consumed by an external iteration mechanism such as a foreach() loop or a function like iterator_to_array(). Without such iteration, the recursive yielding will not be triggered or evaluated.
See Also¶
recursive yielding functions [Try me]
PHP Features¶
Last updated: 14 July 2026