The Generator class
Learn the Generator class's current(), next() and send() methods.
The Generator class methods
When a function containing yield is called, a Generator object is returned. Generator implements the Iterator interface; current() gives the current value, next() moves forward, valid() checks whether more values remain.
key() returns the yield's key; rewind() restarts (only before iteration begins). With these methods you can drive a generator manually.
Sending values back with send()
The send($value) method sends a value back to the paused yield expression. yield not only produces a value, it can also receive one as an expression: $received = yield $value;.
This lets you set up two-way communication with the generator. In send('hello'), 'hello' becomes the result of the yield expression and execution advances to the next yield.
Exercise Drive the generator manually
Create a generator with $gen = countUp(5, 8). Inside a while ($gen->valid()) loop, print the value with current(), then advance with next().
Show example solution
Set up a while ($gen->valid()) loop. Inside it, print the value with echo $gen->current() . "\n"; then advance with $gen->next();.
Example solution:
<?php
function countUp(int $from, int $to): \Generator {
for ($i = $from; $i <= $to; $i++) {
yield $i;
}
}
$gen = countUp(5, 8);
while ($gen->valid()) {
echo $gen->current() . "\n";
$gen->next();
}
Test yourself
-
Get the first value with current()
$gen = countUp(1, 3); echo $gen->____();Show answer
$gen = countUp(1, 3); echo $gen->current(); -
What does the send() method do?
- Sends a value to the generator, becomes the result of the yield expression
- Restarts the generator from the beginning
- Permanently closes the generator
- Only returns the next value, without sending anything
Show answer
Sends a value to the generator, becomes the result of the yield expression — Correct. send($value) advances from the paused yield, passing $value as the result of the yield expression.
-
Match the generator methods
- current()
- Returns the current yield value
- next()
- Advances to the next yield
- valid()
- Checks if more values remain
- send()
- Sends a value back to yield