In a post to his site Niklas Keller provides an introduction to generators in PHP. Generators provide more "just in time" functionality for looping (iterators) without the need to create a separate class to handle it.
Generators have been added to PHP in version 5.5, yet the have received rather low attention. The PHP 5.5 migration guide introduced them as way to implement simple iterators.
He shows the comparison of generators versus a foreach
loop and discusses how the yield
statement works and what benefits the generator gives over normal looping. He refactors the example to get a clearer picture into what's happening inside the generator, outputting a few strings when the next value is fetched. He then suggests that generators that are just used as iterators are "boring" and covers some more interesting features and uses (including handling of async operations).