Simple PHP generator instance, php Generator
Generally, when you iterate a set of data, you need to create a data. If the array is large, it will consume a lot of performance, and even cause insufficient memory.
Copy codeThe Code is as follows:
// Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in E: \ php \ test \ index. php on line 5
Range (1, 100000000 );
PHP5.5 implements the generator. Every time an array element is generated, it is returned with the yield keyword, And the execution function is paused. When the next method is executed, it will continue to be executed from the last position where yield is located, in the following example, only the intermediate variable $ I is generated.
Copy codeThe Code is as follows:
Function xrange ($ start, $ limit, $ step = 1 ){
For ($ I = $ start; $ I <= $ limit; $ I ++ = $ step ){
Yield $ I;
}
}
Foreach (xrange (1, 9, 1) as $ number ){
Echo "$ number ";
}