Home >Backend Development >PHP Tutorial >php generator introduction and examples

php generator introduction and examples

伊谢尔伦
伊谢尔伦Original
2016-11-23 09:11:561228browse

Note: Generator is only supported by PHP5.5 and above.

Generators provide an easier way to implement simple object iteration without the performance overhead and complexity of implementing a class with the Iterator interface.

Generators allow you to write code in a foreach block to iterate over a set of data without creating an array in memory, which would hit your memory limit or take up considerable processing time. Instead, you can write a generator function, just like a normal custom function, and instead of a normal function returning only once, the generator can yield as many times as needed to generate values ​​that need to be iterated over.

A simple example is to use a generator to reimplement the range() function. The standard range() function needs to generate an array in memory for each return value, which results in a very large array. For example, calling range(0, 1000000) will cause the memory usage to exceed 100 MB.

As an alternative, we can implement an xrange() generator that only requires enough memory to create the Iterator object and track the current state of the generator internally, thus requiring less than 1K bytes of memory.

Example #1 Implement range() as a generator

<?php
    function xrange($start, $limit, $step = 1) {
        if ($start < $limit) {
            if ($step <= 0) {
                throw new LogicException(&#39;step必须是正数&#39;);
            }
            for ($i = $start; $i <= $limit; $i += $step) {
                yield $i;
            }
        } else {
            if ($step >= 0) {
                throw new LogicException(&#39;step必须是负数&#39;);
            }
            for ($i = $start; $i >= $limit; $i += $step) {
                yield $i;
            }
        }
    }
    /* 注意range() 和 xrange() 的结果在下面的统一输出中. */
    echo &#39;来自range()的单个奇数: &#39;;
    foreach (range(1, 9, 2) as $number) {
        echo "$number ";
    }
    echo "\n";
    echo &#39;来自xrange()的单个奇数 &#39;;
    foreach (xrange(1, 9, 2) as $number) {
        echo "$number ";
    }
?>

The above routine will output:

Single digit odd numbers from range():  1 3 5 7 9 
Single digit odd numbers from xrange(): 1 3 5 7 9


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