Advantages of Generators
suggest changePHP 5.5 introduces generators and the yield keyword. A generator function can pause and resume, which is also how some coroutine libraries make asynchronous code look synchronous.
The yield expression is responsible for giving control back to the calling code and providing a point of resumption at that place. One can send a value along the yield instruction. The return value of this expression is either null or the value which was passed to Generator::send().
function reverse_range($i) {
// the mere presence of the yield keyword in this function makes this a Generator
do {
// $i is retained between resumptions
print yield $i;
} while (--$i > 0);
}
$gen = reverse_range(5);
print $gen->current();
$gen->send("injected!"); // send also resumes the Generator
// foreach() would call rewind() and throw, because this generator has already started
while ($gen->valid()) {
echo $gen->current();
$gen->next();
}
// Output: 5injected!4321
This mechanism can be used by a coroutine implementation to wait for Awaitables yielded by the Generator (by registering itself as a callback for resolution) and continue execution of the Generator as soon as the Awaitable is resolved.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents