The generator provides an easier way to implement simple object iteration, but does not implement the performance overhead and complexity of a class with an Iterator interface. Note: PHP5.5 and later versions support generators.
The generator provides an easier way to implement simple object iteration, but does not implement the performance overhead and complexity of a class with an Iterator interface.
The generator allows you to write code in the foreach code block to iterate a group of data without creating an array in the memory. This will limit your memory or occupy a considerable processing time. On the contrary, you can write a generator function, just like a normal custom function. different from a normal function, a generator can return multiple times as needed, to generate the value to be iterated.
A simple example is to use a generator to re-implement the range () function. The standard range () function generates an array for each returned value in the memory and generates a large array. For example, calling range (0, 1000000) will cause memory usage to exceed 100 MB.
As an alternative, we can implement an xrange () generator. we only need enough memory to create an Iterator object and track the current state of the generator internally, this requires less than 1 kB of memory.
Example #1 implement range () as a generator
= 0) {throw new LogicException ('step must be a negative number');} for ($ I = $ start; $ I >=$ limit; $ I + = $ step) {yield $ I ;}}/ * Note that the results of range () and xrange () are in the unified output below. */echo 'single odd number from range (): '; foreach (range (1, 9, 2) as $ number) {echo "$ number ";} echo "\ n"; echo 'single odd number from 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