Skip to content

PHP Generator

Last updated on June 22, 2015

Generators compute and yield iteration values on-demand unlike regular PHP iterators. Means generator returns a sequence of values with yield instead of a single value with return. When the yield statement of a generator function is executed, the argument of the yield statement is yielded and the execution of the generator function is suspended. The execution of the generator function is resumed when the next value is requested.

Standard PHP iterators often iterate in-memory and creates precompiled data sets. And this is inefficient with large data sets. So to save valuable memory we use generators to compute and yield subsequent values on the fly.

Notes:
1 .Generators never knows the next iteration value until asked and it is impossible to rewind or fast-forward a generator. You can only iterate in one direction (forward).
2. You cannot iterate the same generator more the once. But you can rewind and clone a generator.


The above example will output:

value1 
value2 
value3

When you invoke the Generator function, it will return the object of the generator . By using foreach control structure, you can iterate over the generator object. During each iteration PHP ask the generator instance to compute and provide the value. And coolest thing here is, generator pauses its internal state whenever it yields a value. The generator resumes internal state when it is asked for the next value. The generator continues pausing and resuming until it reaches the end of its function definition or an empty return.

Another Example :

 

The above example will output:

1
2
3
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments