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

PHP生成器简单实例

WBOY
WBOYOriginal
2016-06-13 09:04:241131browse

PHP生成器简单实例

   这篇文章主要介绍了PHP生成器简单实例,本文讲解了range、xrange函数的基本使用实例,需要的朋友可以参考下

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

   代码如下:

  //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 ";

  }

Statement:
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