InterviewSolution
| 1. |
What are generators? |
|
Answer» Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface. A generator allows you to write code that uses FOREACH to iterate over a set of data without NEEDING to BUILD an array in memory, which may CAUSE you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over. <?php function nums() { echo "The generator has startedn"; for ($i = 0; $i < 5; ++$i) { yield $i; echo "Yielded $in"; } echo "The generator has endedn"; } foreach (nums() as $v); |
|