我最近无意中发现了这段代码:

function xrange($min, $max) 
{
    for ($i = $min; $i <= $max; $i++) {
        yield $i;
    }
}

我以前从未见过这个yield关键字。试着运行我得到的代码

解析错误:语法错误,意外的T_VARIABLE在x行

那么yield关键字是什么呢?它是有效的PHP吗?如果是,我该怎么用呢?


当前回答

这个函数使用yield:

function a($items) {
    foreach ($items as $item) {
        yield $item + 1;
    }
}

它和这个几乎一样,没有:

function b($items) {
    $result = [];
    foreach ($items as $item) {
        $result[] = $item + 1;
    }
    return $result;
}

唯一的区别是a()返回一个生成器,而b()只是一个简单的数组。你可以在两者上进行迭代。

另外,第一个不分配完整的数组,因此内存需求更少。

其他回答

下面的代码说明了如何使用生成器在完成之前返回一个结果,而不像传统的非生成器方法在完整迭代之后返回一个完整的数组。使用下面的生成器,值在准备就绪时返回,不需要等待数组被完全填充:

<?php 

function sleepiterate($length) {
    for ($i=0; $i < $length; $i++) {
        sleep(2);
        yield $i;
    }
}

foreach (sleepiterate(5) as $i) {
    echo $i, PHP_EOL;
}

使用yield,您可以很容易地描述单个函数中多个任务之间的断点。就是这样,没什么特别的。

$closure = function ($injected1, $injected2, ...){
    $returned = array();
    //task1 on $injected1
    $returned[] = $returned1;
//I need a breakpoint here!!!!!!!!!!!!!!!!!!!!!!!!!
    //task2 on $injected2
    $returned[] = $returned2;
    //...
    return $returned;
};
$returned = $closure($injected1, $injected2, ...);

如果task1和task2高度相关,但你需要在它们之间设置一个断点来做其他事情:

处理数据库行之间的空闲内存 运行对下一个任务提供依赖关系的其他任务,但通过理解当前代码,这些任务是不相关的 执行异步调用并等待结果 等等……

生成器是最好的解决方案,因为你不需要把你的代码分割成许多闭包,或者与其他代码混合,或者使用回调等等……您只需使用yield来添加一个断点,如果准备好了,可以从该断点继续。

添加没有生成器的断点:

$closure1 = function ($injected1){
    //task1 on $injected1
    return $returned1;
};
$closure2 = function ($injected2){
    //task2 on $injected2
    return $returned1;
};
//...
$returned1 = $closure1($injected1);
//breakpoint between task1 and task2
$returned2 = $closure2($injected2);
//...

使用生成器添加断点

$closure = function (){
    $injected1 = yield;
    //task1 on $injected1
    $injected2 = (yield($returned1));
    //task2 on $injected2
    $injected3 = (yield($returned2));
    //...
    yield($returnedN);
};
$generator = $closure();
$returned1 = $generator->send($injected1);
//breakpoint between task1 and task2
$returned2 = $generator->send($injected2);
//...
$returnedN = $generator->send($injectedN);

注意:使用生成器很容易犯错误,所以在实现它们之前一定要编写单元测试! 注2:在无限循环中使用生成器就像写一个无限长的闭包……

这个函数使用yield:

function a($items) {
    foreach ($items as $item) {
        yield $item + 1;
    }
}

它和这个几乎一样,没有:

function b($items) {
    $result = [];
    foreach ($items as $item) {
        $result[] = $item + 1;
    }
    return $result;
}

唯一的区别是a()返回一个生成器,而b()只是一个简单的数组。你可以在两者上进行迭代。

另外,第一个不分配完整的数组,因此内存需求更少。

在实现PHP IteratorAggregate接口时,yield关键字将很有用。查看文档,有几个使用ArrayIterator或yield的例子。

另一个例子是php-ds/polyfill repo: https://github.com/php-ds/polyfill/blob/e52796c50aac6e6cfa6a0e8182943027bacbe187/src/Traits/GenericSequence.php#L359

这个想法类似于下面的例子:

class Collection implements \IteratorAggregate
{
    private $array = [];

    public function push(...$values)
    {
        array_push($this->array, ...$values);
    }

    public function getIterator()
    {
        foreach ($this->array as $value) {
            yield $value;
        }
    }
}

$collection = new Collection();
$collection->push('apple', 'orange', 'banana');

foreach ($collection as $key => $value) {
    echo sprintf("[%s] => %s\n", $key, $value);
}

输出:

[0] => apple
[1] => orange
[2] => banana

yield关键字用于定义PHP 5.5中的“生成器”。 好的,那么什么是发电机?

从php.net:

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface. A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.

从这里开始:发电机=发电机,其他函数(只是一个简单的函数)=函数。

因此,它们在以下情况下很有用:

you need to do things simple (or simple things); generator is really much simplier then implementing the Iterator interface. other hand is, ofcource, that generators are less functional. compare them. you need to generate BIG amounts of data - saving memory; actually to save memory we can just generate needed data via functions for every loop iteration, and after iteration utilize garbage. so here main points is - clear code and probably performance. see what is better for your needs. you need to generate sequence, which depends on intermediate values; this is extending of the previous thought. generators can make things easier in comparison with functions. check Fibonacci example, and try to make sequence without generator. Also generators can work faster is this case, at least because of storing intermediate values in local variables; you need to improve performance. they can work faster then functions in some cases (see previous benefit);