What is generator in PHP?
A generator is basically a normal function, but instead of returning a value it yields as many values as it needs to. It looks like a function but acts as an iterator. Generators use the yield keyword instead of return.
Sample Example -
<?php
function generator() {
echo "Generator started";
for ($i = 0; $i < 5; ++$i) {
yield $i;
echo "Yielded $in";
}
echo "Generator ended";
}
foreach (generator() as $g);
Comments
Post a Comment