Home > php教程 > php手册 > PHP生成器简单实例,php生成器

PHP生成器简单实例,php生成器

WBOY
Release: 2016-06-13 09:04:31
Original
914 people have browsed it

PHP生成器简单实例,php生成器

一般你在迭代一组数据的时候,需要创建一个数据,假设数组很大,则会消耗很大性能,甚至造成内存不足。
复制代码 代码如下:
//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实现了生成器,每当产生一个数组元素则用yield关键词返回,并且执行函数暂停,当执行函数next方法时,则会从上一次被yield的位置开始继续执行,如下例子,只会产生中间变量$i
复制代码 代码如下:
function xrange($start, $limit, $step = 1) {
    for ($i = $start; $i         yield $i;
    }
}
 
foreach (xrange(1, 9, 1) as $number) {
    echo "$number ";
}

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template