Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Niklas Keller:
An Introduction to Generators in PHP
Sep 21, 2017 @ 12:57:15

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).

tagged: generator tutorial introduction yield async looping interator

Link: http://blog.kelunik.com/2017/09/14/an-introduction-to-generators-in-php.html