PHP Generator Simple instance, PHP generator
Generally when you iterate over a set of data, you need to create a data, assuming that the array is large, it consumes a lot of performance, or even causes memory shortage.
Copy the Code code as follows:
Fatal error:allowed memory size of 134217728 bytes exhausted (tried to allocate + bytes) in E:\php\test\index.php on L INE 5
Range (1, 100000000);
PHP5.5 implements the generator, each time an array element is returned with a yield keyword, and the execution function is paused, and when the function next method is executed, it proceeds from the last yield position, as shown in the following example, only intermediate variables are generated $i
Copy the Code code 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";
}
http://www.bkjia.com/PHPjc/998817.html www.bkjia.com true http://www.bkjia.com/PHPjc/998817.html techarticle PHP Generator Simple example, PHP generator generally when you iterate a set of data, you need to create a data, assuming that the array is large, it will consume a lot of performance, or even cause memory shortage. ...