Delegation with yield from
Learn to delegate another generator or array with yield from.
What is yield from?
yield from delegates another generator, array or Traversable object. It yields all values of the inner generator one by one; instead of writing each separately, you forward them in one line.
This lets you build nested generators. An outer generator can call several sub-generators in turn and emit their values as a single stream.
Nested generators
A generator can call another generator with yield from. The outer generator keeps emitting the inner generator's values as if they were its own.
This reduces code duplication and breaks tasks into small pieces. Each sub-generator carries its own responsibility; the outer generator only combines the flow.
Exercise Delegation with yield from
Write inner(): \Generator: yield the values 'x', 'y', 'z'. Write outer(): \Generator: delegate inner with yield from inner(), then yield 'w'. Iterate outer() with foreach and print each value.
Show example solution
In inner, yield 'x', 'y', 'z'. In outer, first delegate with yield from inner(); then add yield 'w';. Then iterate with foreach (outer() as $value) and echo $value . "\n";
Example solution:
<?php
function inner(): \Generator {
yield "x";
yield "y";
yield "z";
}
function outer(): \Generator {
yield from inner();
yield "w";
}
foreach (outer() as $value) {
echo $value . "\n";
}
Test yourself
-
Match the yield from concepts
- yield from
- Delegates another generator
- yield
- Produces a single value
- yield from $arr
- Yields all array elements
-
What does yield from $arr do?
- Produces only the first element of the array
- Produces all elements of the array one by one
- Copies the array into a new generator
- Does nothing
Show answer
Produces all elements of the array one by one — Correct. yield from $arr yields each element of the array in turn.
-
outer delegates to inner
function inner(): \Generator { yield 'a'; yield 'b'; } function outer(): \Generator { ____ inner(); yield 'c'; }Show answer
function inner(): \Generator { yield 'a'; yield 'b'; } function outer(): \Generator { yield from inner(); yield 'c'; }