Last updated 2024-04-04 05:25:47

What Is Generator In Programming?

A generator is a special type of Iterator [→] that produces results more progressively instead of all at once. It produces values on the fly as they are needed, potentially saving memory and resources compared to generating an entire sequence upfront.

Here's an example of a generator in PHP:

01: function myGenerator() { 02: yield 1; 03: yield 2; 04: yield 3; 05: } 06: 07: // Using the generator to iterate over its values 08: $gen = myGenerator(); 09: foreach ($gen as $value) { 10: echo $value . PHP_EOL; 11: }

In this example:

  • The myGenerator() function is defined as a generator using the yield keyword.
  • Each yield statement within the function produces a value for the generator.
  • The $gen variable is assigned the generator object returned by myGenerator().
  • The foreach loop iterates over the values generated by $gen, printing each value.

When myGenerator() is called, it doesn't execute the code inside the function immediately. Instead, it returns an iterator object that can be iterated over. Each time the foreach loop requests the next value from the generator, the function is executed until it reaches a yield statement, producing the next value in the sequence. This allows for the lazy evaluation of the sequence of values.

Here is another article you might like 😊 "Diary Of Insights: A Documentation Of My Discoveries"