Rumah >pembangunan bahagian belakang >tutorial php >PHP的学习--生成器Generators,--生成器generators_PHP教程
(PHP 5 >= 5.5.0, PHP 7)
生成器提供了一种更容易的方法来实现简单的对象迭代,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大大降低。
生成器允许你在 foreach 代码块中写代码来迭代一组数据而不需要在内存中创建一个数组, 那会使你的内存达到上限,或者会占据可观的处理时间。相反,你可以写一个生成器函数,就像一个普通的自定义函数一样, 和普通函数只返回一次不同的是, 生成器可以根据需要 yield 多次,以便生成需要迭代的值。
一个简单的例子就是使用生成器来重新实现 range() 函数。 标准的 range() 函数需要在内存中生成一个数组包含每一个在它范围内的值,然后返回该数组, 结果就是会产生多个很大的数组。 比如,调用 range(0, 1000000) 将导致内存占用超过 100 MB。
做为一种替代方法, 我们可以实现一个 xrange() 生成器, 只需要足够的内存来创建 Iterator 对象并在内部跟踪生成器的当前状态,这样只需要不到1K字节的内存。
Example #1 将 range() 实现为生成器
<?<span>php </span><span>function</span> xrange(<span>$start</span>, <span>$limit</span>, <span>$step</span> = 1<span>) { </span><span>if</span> (<span>$start</span> < <span>$limit</span><span>) { </span><span>if</span> (<span>$step</span> <= 0<span>) { </span><span>throw</span> <span>new</span> LogicException('Step must be +ve'<span>); } </span><span>for</span> (<span>$i</span> = <span>$start</span>; <span>$i</span> <= <span>$limit</span>; <span>$i</span> += <span>$step</span><span>) { yield </span><span>$i</span><span>; } } </span><span>else</span><span> { </span><span>if</span> (<span>$step</span> >= 0<span>) { </span><span>throw</span> <span>new</span> LogicException('Step must be -ve'<span>); } </span><span>for</span> (<span>$i</span> = <span>$start</span>; <span>$i</span> >= <span>$limit</span>; <span>$i</span> += <span>$step</span><span>) { yield </span><span>$i</span><span>; } } } </span><span>/*</span><span> * 注意下面range()和xrange()输出的结果是一样的。 </span><span>*/</span> <span>echo</span> 'Single digit odd numbers from range(): '<span>; </span><span>foreach</span> (<span>range</span>(1, 9, 2) <span>as</span> <span>$number</span><span>) { </span><span>echo</span> "<span>$number</span> "<span>; } </span><span>echo</span> "\n"<span>; </span><span>echo</span> 'Single digit odd numbers from xrange(): '<span>; </span><span>foreach</span> (xrange(1, 9, 2) <span>as</span> <span>$number</span><span>) { </span><span>echo</span> "<span>$number</span> "<span>; } </span>?>
以上例程会输出:
Single digit odd numbers from range(): <span>1</span> <span>3</span> <span>5</span> <span>7</span> <span>9</span><span> Single digit odd numbers from xrange(): </span><span>1</span> <span>3</span> <span>5</span> <span>7</span> <span>9</span>
When a generator function is called for the first time, an object of the internal Generator class is returned. This object implements the Iterator interface in much the same way as a forward-only iterator object would, and provides methods that can be called to manipulate the state of the generator, including sending values to and returning values from it.
一个生成器函数看起来像一个普通的函数,不同的是普通函数返回一个值,而一个生成器可以 yield 生成许多它所需要的值。
当一个生成器被调用的时候,它返回一个可以被遍历的对象.当你遍历这个对象的时候(例如通过一个foreach循环),PHP 将会在每次需要值的时候调用生成器函数,并在产生一个值之后保存生成器的状态,这样它就可以在需要产生下一个值的时候恢复调用状态。
一旦不再需要产生更多的值,生成器函数可以简单退出,而调用生成器的代码还可以继续执行,就像一个数组已经被遍历完了。
Note:
一个生成器不可以返回值: 这样做会产生一个编译错误。然而return空是一个有效的语法并且它将会终止生成器继续执行。
yield关键字
生成器函数的核心是yield关键字。它最简单的调用形式看起来像一个return申明,不同之处在于普通return会返回值并终止函数的执行,而yield会返回一个值给循环调用此生成器的代码并且只是暂停执行生成器函数。
Example #1 一个简单的生成值的例子
<?<span>php </span><span>function</span><span> gen_one_to_three() { </span><span>for</span> (<span>$i</span> = 1; <span>$i</span> <= 3; <span>$i</span>++<span>) { </span><span>//</span><span>注意变量$i的值在不同的yield之间是保持传递的。</span> yield <span>$i</span><span>; } } </span><span>$generator</span> =<span> gen_one_to_three(); </span><span>foreach</span> (<span>$generator</span> <span>as</span> <span>$value</span><span>) { </span><span>echo</span> "<span>$value</span>\n"<span>; } </span>?>以上例程会输出:
<span>1</span> <span>2</span> <span>3</span>Note:
在内部会为生成的值配对连续的整型索引,就像一个非关联的数组。
如果在一个表达式上下文(例如在一个赋值表达式的右侧)中使用yield,你必须使用圆括号把yield申明包围起来。 例如这样是有效的:
<span>$data</span> = (yield <span>$value</span>);而这样就不合法,并且在PHP5中会产生一个编译错误:
<span>$data</span> = yield <span>$value</span>;The parenthetical restrictions do not apply in PHP 7.
这个语法可以和生成器对象的Generator::send()方法配合使用。
指定键名来生成值
PHP的数组支持关联键值对数组,生成器也一样支持。所以除了生成简单的值,你也可以在生成值的时候指定键名。
如下所示,生成一个键值对与定义一个关联数组十分相似。
Example #2 生成一个键值对
<?<span>php </span><span>/*</span><span> * 下面每一行是用分号分割的字段组合,第一个字段将被用作键名。 </span><span>*/</span> <span>$input</span> = <<<'EOF' 1<span>;PHP;Likes dollar signs </span>2<span>;Python;Likes whitespace </span>3<span>;Ruby;Likes blocks EOF; </span><span>function</span> input_parser(<span>$input</span><span>) { </span><span>foreach</span> (<span>explode</span>("\n", <span>$input</span>) <span>as</span> <span>$line</span><span>) { </span><span>$fields</span> = <span>explode</span>(';', <span>$line</span><span>); </span><span>$id</span> = <span>array_shift</span>(<span>$fields</span><span>); yield </span><span>$id</span> => <span>$fields</span><span>; } } </span><span>foreach</span> (input_parser(<span>$input</span>) <span>as</span> <span>$id</span> => <span>$fields</span><span>) { </span><span>echo</span> "<span>$id</span>:\n"<span>; </span><span>echo</span> " <span>$fields</span>[0]\n"<span>; </span><span>echo</span> " <span>$fields</span>[1]\n"<span>; } </span>?>以上例程会输出:
<span>1</span><span>: PHP Likes dollar signs </span><span>2</span><span>: Python Likes whitespace </span><span>3</span><span>: Ruby Likes blocks</span>和之前生成简单值类型一样,在一个表达式上下文中生成键值对也需要使用圆括号进行包围:
<span>$data</span> = (yield <span>$key</span> => <span>$value</span>);生成null值
Yield可以在没有参数传入的情况下被调用来生成一个
NULL
值并配对一个自动的键名。Example #3 生成
NULL
s<?<span>php </span><span>function</span><span> gen_three_nulls() { </span><span>foreach</span> (<span>range</span>(1, 3) <span>as</span> <span>$i</span><span>) { yield; } } </span><span>var_dump</span><span>(iterator_to_array(gen_three_nulls())); </span>?>以上例程会输出:
array(<span>3</span><span>) { [</span><span>0</span>]=><span> NULL [</span><span>1</span>]=><span> NULL [</span><span>2</span>]=><span> NULL }</span>使用引用来生成值
生成函数可以像使用值一样来使用引用生成。这个和returning references from functions(从函数返回一个引用)一样:通过在函数名前面加一个引用符号。
Example #4 使用引用来生成值
<?<span>php </span><span>function</span> &<span>gen_reference() { </span><span>$value</span> = 3<span>; </span><span>while</span> (<span>$value</span> > 0<span>) { yield </span><span>$value</span><span>; } } </span><span>/*</span><span> * 我们可以在循环中修改$number的值,而生成器是使用的引用值来生成,所以gen_reference()内部的$value值也会跟着变化。 </span><span>*/</span> <span>foreach</span> (gen_reference() <span>as</span> &<span>$number</span><span>) { </span><span>echo</span> (--<span>$number</span>).'... '<span>; } </span>?>以上例程会输出:
<span>2</span>... <span>1</span>... <span>0</span>...Generator delegation via yield from ¶
In PHP 7, generator delegation allows you to yield values from another generator, Traversable object, or array by using the yield from keyword. The outer generator will then yield all values from the inner generator, object, or array until that is no longer valid, after which execution will continue in the outer generator.
If a generator is used with yield from, the yield from expression will also return any value returned by the inner generator.
Example #5 Basic use of yield from
<?<span>php </span><span>function</span><span> count_to_ten() { yield </span>1<span>; yield </span>2<span>; yield from [</span>3, 4<span>]; yield from </span><span>new</span> ArrayIterator([5, 6<span>]); yield from seven_eight(); yield </span>9<span>; yield </span>10<span>; } </span><span>function</span><span> seven_eight() { yield </span>7<span>; yield from eight(); } </span><span>function</span><span> eight() { yield </span>8<span>; } </span><span>foreach</span> (count_to_ten() <span>as</span> <span>$num</span><span>) { </span><span>echo</span> "<span>$num</span> "<span>; } </span>?>以上例程会输出:
<span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> <span>6</span> <span>7</span> <span>8</span> <span>9</span> <span>10</span>Example #6 yield from and return values
<?<span>php </span><span>function</span><span> count_to_ten() { yield </span>1<span>; yield </span>2<span>; yield from [</span>3, 4<span>]; yield from </span><span>new</span> ArrayIterator([5, 6<span>]); yield from seven_eight(); </span><span>return</span><span> yield from nine_ten(); } </span><span>function</span><span> seven_eight() { yield </span>7<span>; yield from eight(); } </span><span>function</span><span> eight() { yield </span>8<span>; } </span><span>function</span><span> nine_ten() { yield </span>9<span>; </span><span>return</span> 10<span>; } </span><span>$gen</span> =<span> count_to_ten(); </span><span>foreach</span> (<span>$gen</span> <span>as</span> <span>$num</span><span>) { </span><span>echo</span> "<span>$num</span> "<span>; } </span><span>echo</span> <span>$gen</span>-><span>getReturn(); </span>?>以上例程会输出:
<span>1</span> <span>2</span> <span>3</span> <span>4</span> <span>5</span> <span>6</span> <span>7</span> <span>8</span> <span>9</span> <span>10</span>Comparing generators with Iterator objects
The primary advantage of generators is their simplicity. Much less boilerplate code has to be written compared to implementing an Iterator class, and the code is generally much more readable. For example, the following function and class are equivalent:
<?<span>php </span><span>function</span> getLinesFromFile(<span>$fileName</span><span>) { </span><span>if</span> (!<span>$fileHandle</span> = <span>fopen</span>(<span>$fileName</span>, 'r'<span>)) { </span><span>return</span><span>; } </span><span>while</span> (<span>false</span> !== <span>$line</span> = <span>fgets</span>(<span>$fileHandle</span><span>)) { yield </span><span>$line</span><span>; } </span><span>fclose</span>(<span>$fileHandle</span><span>); } </span><span>//</span><span> versus...</span> <span>class</span> LineIterator <span>implements</span><span> Iterator { </span><span>protected</span> <span>$fileHandle</span><span>; </span><span>protected</span> <span>$line</span><span>; </span><span>protected</span> <span>$i</span><span>; </span><span>public</span> <span>function</span> __construct(<span>$fileName</span><span>) { </span><span>if</span> (!<span>$this</span>->fileHandle = <span>fopen</span>(<span>$fileName</span>, 'r'<span>)) { </span><span>throw</span> <span>new</span> RuntimeException('Couldn\'t open file "' . <span>$fileName</span> . '"'<span>); } } </span><span>public</span> <span>function</span> <span>rewind</span><span>() { </span><span>fseek</span>(<span>$this</span>->fileHandle, 0<span>); </span><span>$this</span>->line = <span>fgets</span>(<span>$this</span>-><span>fileHandle); </span><span>$this</span>->i = 0<span>; } </span><span>public</span> <span>function</span><span> valid() { </span><span>return</span> <span>false</span> !== <span>$this</span>-><span>line; } </span><span>public</span> <span>function</span> <span>current</span><span>() { </span><span>return</span> <span>$this</span>-><span>line; } </span><span>public</span> <span>function</span> <span>key</span><span>() { </span><span>return</span> <span>$this</span>-><span>i; } </span><span>public</span> <span>function</span> <span>next</span><span>() { </span><span>if</span> (<span>false</span> !== <span>$this</span>-><span>line) { </span><span>$this</span>->line = <span>fgets</span>(<span>$this</span>-><span>fileHandle); </span><span>$this</span>->i++<span>; } } </span><span>public</span> <span>function</span><span> __destruct() { </span><span>fclose</span>(<span>$this</span>-><span>fileHandle); } } </span>?>This flexibility does come at a cost, however: generators are forward-only iterators, and cannot be rewound once iteration has started. This also means that the same generator can't be iterated over multiple times: the generator will need to either be rebuilt by calling the generator function again, or cloned via the clone keyword.
摘自:http://php.net/manual/zh/language.generators.php