Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to.

When a generator function is called, it returns an object that can be iterated over. When you iterate over that object (for instance, via a foreach loop), PHP will call the generator function each time it needs a value, then saves the state of the generator when the generator yields a value so that it can be resumed when the next value is required.

Once there are no more values to be yielded, then the generator function can simply exit, and the calling code continues just as if an array has run out of values.

• A mechanism to generate iterators

• A generator function returns multiple values

• Individual values are returned using the yield keyword

• Generator may use return for the final return expression; the generator´s getreturn() method gives access to this value.

function myGenerator() {
for ($i = 1; $i <= 10; $i++) {
yield $i;


Leave a Reply

Your email address will not be published. Required fields are marked *