Just a regular function, which yields things (but can return them sometimes as well).
Steps:
-
Create a function that
yieldsthings instead of `returns˙. If you need it to generate numbers, it should yield numbers. If you’re traversing a large file, it might yield lines, one by one. -
Call the function, and store the result in a variable. Good job. This variable is now a
generator. Every time there’s ayieldin a function, calling it would result in aGeneratorobject. -
Use this generator in a loop, or manually as shown below, to perform some actions. Generators implement
Iteratorinterface, which means they have access to all of theIteratormethods. -
rewindcan be thought of like this - start a new cycle, and call the code up until the first yield. It allows us to perform checks before trying to yield the value in our loops.rewindis not going to revert generator to the initial state. This is not possible with PHP generators. -
It’s possible to return a value in your generator, using the
returnkeyword. Result of the return can be fetched withgetReturn()method. However, callinggetReturnwen generator has not yet returned a value, would thron an exception.
function nrange($from, $to) {
if ($from > $to) {
throw new \Exception("Wrong range.");
}
for ($i = $from; $i < $to; $i++) {
yield $i;
}
return 20;
}
$generator = nrange(0, 10);
$generator->rewind();
while ($generator->valid())
{
$key = $generator->key();
$value = $generator->current();
// echo $generator->getReturn(); - will throw an exception as generator has not yet finished (no return value)
echo $value . " ";
$generator->next();
}
echo $generator->getReturn();
$generator = nrange(10, 1);
$generator->rewind(); // will throw an exception because of the range being wrong
Most common place where you’d use generators is for iteration over objects/values, but instead of hodling all of them in memory, they would be yielded one at a time.
You know I always wanted to pretend that I was an architect.
– George C.