Home > Article > Backend Development > php generator introduction and examples
Note: Generator is only supported by PHP5.5 and above.
Generators provide an easier way to implement simple object iteration without the performance overhead and complexity of implementing a class with the Iterator interface.
Generators allow you to write code in a foreach block to iterate over a set of data without creating an array in memory, which would hit your memory limit or take up considerable processing time. Instead, you can write a generator function, just like a normal custom function, and instead of a normal function returning only once, the generator can yield as many times as needed to generate values that need to be iterated over.
A simple example is to use a generator to reimplement the range() function. The standard range() function needs to generate an array in memory for each return value, which results in a very large array. For example, calling range(0, 1000000) will cause the memory usage to exceed 100 MB.
As an alternative, we can implement an xrange() generator that only requires enough memory to create the Iterator object and track the current state of the generator internally, thus requiring less than 1K bytes of memory.
Example #1 Implement range() as a generator
<?php function xrange($start, $limit, $step = 1) { if ($start < $limit) { if ($step <= 0) { throw new LogicException('step必须是正数'); } for ($i = $start; $i <= $limit; $i += $step) { yield $i; } } else { if ($step >= 0) { throw new LogicException('step必须是负数'); } for ($i = $start; $i >= $limit; $i += $step) { yield $i; } } } /* 注意range() 和 xrange() 的结果在下面的统一输出中. */ echo '来自range()的单个奇数: '; foreach (range(1, 9, 2) as $number) { echo "$number "; } echo "\n"; echo '来自xrange()的单个奇数 '; foreach (xrange(1, 9, 2) as $number) { echo "$number "; } ?>
The above routine will output:
Single digit odd numbers from range(): 1 3 5 7 9 Single digit odd numbers from xrange(): 1 3 5 7 9