Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the iterator interface.
OK, here is a more detailed and easy-to-understand definition from the same source, php.net:
A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.
For example, you can simply write a function returning a lot of different numbers or values. But, the problem is that if a lot of different values means millions of values, then making and returning an array with those values is not efficient, because it will consume a lot of memory. So in that case, using generator makes more sense.
To understand, see this example:
/* function to return generator */ function getValues($max){ for($i=0; $i<$max; $i++ ){ yield $i*2; } }
// Using generator foreach(getValues(99999) as $value){ echo "Values: $value <br>"; }
As you can see, there is a yield statement in code. It is just like the return statement but in generator, yield does not return all the values at once. It only returns a value every time yield executes, and yield is called only when the generator function is called. Also, every time yield executes, it resumes the code execution from where it was stopped the last time.
Now we have an understanding of generators, so let's look into the PHP7 features related to generators.