Overview - Generator function execution model
What is it?
A generator function in PHP is a special kind of function that can pause its execution and resume later, producing a sequence of values over time instead of computing them all at once. It uses the 'yield' keyword to return values one at a time, allowing efficient memory use. This lets you work with large data sets or streams without loading everything into memory. Generators behave like iterators but are simpler to write and manage.
Why it matters
Without generators, PHP scripts would need to build entire lists or arrays in memory before processing, which can be slow and use a lot of memory. Generators solve this by producing values on demand, making programs faster and more memory-friendly. This is especially important when dealing with big files, databases, or infinite sequences. Without generators, some tasks would be impractical or inefficient.
Where it fits
Before learning generators, you should understand basic PHP functions, arrays, and loops. Knowing how iterators work helps too. After mastering generators, you can explore advanced topics like asynchronous programming, coroutines, and custom iterator classes.