Home > Backend Development > PHP Tutorial > PHP生成器简单实例_php实例

PHP生成器简单实例_php实例

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 20:15:45
Original
1070 people have browsed it

一般你在迭代一组数据的时候,需要创建一个数据,假设数组很大,则会消耗很大性能,甚至造成内存不足。

复制代码 代码如下:

//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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template