PHP相当于Python的yield运算符

nil*_*amo 19 php python lazy-evaluation

在Python(和其他)中,您可以通过在函数中使用'yield'运算符来递增地处理大量数据.在PHP中以类似的方式做什么?

例如,假设在Python中,如果我想读取一个可能非常大的文件,我可以一次一行地处理每一行(这个例子是设计的,因为它与'for file in file_obj基本相同) "):

def file_lines(fname):
    f = open(fname)
    for line in f:
        yield line
    f.close()

for line in file_lines('somefile'):
    #process the line
Run Code Online (Sandbox Code Playgroud)

我现在正在做的(在PHP中)是我正在使用私有实例变量来跟踪状态,并且每次调用函数时都会相应地执行操作,但似乎必须有更好的方法.

Run*_*ard 18

https://wiki.php.net/rfc/generators上有一个rfc 就是这样,它可能包含在PHP 5.5中.

与此同时,请查看在用户区实施的这种可怜的"发电机功能"的概念验证.

namespace Functional;

error_reporting(E_ALL|E_STRICT);

const BEFORE = 1;
const NEXT = 2;
const AFTER = 3;
const FORWARD = 4;
const YIELD = 5;

class Generator implements \Iterator {
    private $funcs;
    private $args;
    private $key;
    private $result;

    public function __construct(array $funcs, array $args) {
        $this->funcs = $funcs;
        $this->args = $args;
    }

    public function rewind() {
        $this->key = -1;
        $this->result = call_user_func_array($this->funcs[BEFORE], 
                                             $this->args);
        $this->next();
    }

    public function valid() {
        return $this->result[YIELD] !== false;
    }

    public function current() {
        return $this->result[YIELD];
    }

    public function key() {
        return $this->key;
    }

    public function next() {
        $this->result = call_user_func($this->funcs[NEXT], 
                                       $this->result[FORWARD]);
        if ($this->result[YIELD] === false) {
            call_user_func($this->funcs[AFTER], $this->result[FORWARD]);
        }
        ++$this->key;
    }
}

function generator($funcs, $args) {
    return new Generator($funcs, $args);
}

/**
 * A generator function that lazily yields each line in a file.
 */
function get_lines_from_file($file_name) {
    $funcs = array(
        BEFORE => function($file_name) { return array(FORWARD => fopen($file_name, 'r'));   },
        NEXT   => function($fh)        { return array(FORWARD => $fh, YIELD => fgets($fh)); },
        AFTER  => function($fh)        { fclose($fh);                                       },
    );
    return generator($funcs, array($file_name));
}

// Output content of this file with padded linenumbers.
foreach (get_lines_from_file(__FILE__) as $k => $v) {
    echo str_pad($k, 8), $v;
}
echo "\n";
Run Code Online (Sandbox Code Playgroud)

  • 它包含在5.5 Alpha中:https://github.com/php/php-src/blob/php-5.5.0alpha1/NEWS (3认同)

Emi*_*l H 12

PHP有一个直接等价的称为生成器.

旧(前PHP 5.5答案):

不幸的是,没有相应的语言.最简单的方法是使用您正在执行的操作,或创建使用实例变量来维护状态的对象.

但是,如果要将该函数与foreach语句结合使用,则有一个很好的选择:SPL迭代器.它们可以用来实现与python生成器非常相似的东西.

  • 从PHP 5.5开始,生成器*包含在PHP中.所以你现在可以使用它们:)(包括yield关键字!) (2认同)

Lui*_*mim 11

在用任何其他语言(包括PHP)实现之前,我用Python原型化所有内容.我最终使用回调来实现我的目标yield.

function doSomething($callback) 
{
    foreach ($something as $someOtherThing) {
        // do some computations that generates $data

        call_user_func($callback, $data);
    }
}

function myCallback($input)
{
    // save $input to DB 
    // log
    // send through a webservice
    // etc.
    var_dump($input);
}


doSomething('myCallback');
Run Code Online (Sandbox Code Playgroud)

这样每个$data都传递给回调函数,你可以做你想要的.