19

在 Python(和其他)中,您可以通过在函数中使用“yield”运算符来增量处理大量数据。在 PHP 中这样做的类似方法是什么?

例如,假设在 Python 中,如果我想读取一个可能非常大的文件,我可以像这样一次处理每一行(这个例子是人为的,因为它基本上与 'for line 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

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

4

6 回答 6

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";
于 2012-07-15T20:34:16.587 回答
12

PHP 有一个直接的等价物,称为generators

旧的(php 5.5 之前的答案):

不幸的是,没有等效的语言。最简单的方法是要么做你已经在做的事情,要么创建一个使用实例变量来维护状态的对象。

但是,如果您想将该函数与 foreach 语句结合使用,则有一个不错的选择:SPL Iterators。它们可以用来实现与 python 生成器非常相似的东西。

于 2009-07-15T19:25:29.730 回答
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');

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

于 2009-07-15T20:34:15.347 回答
3

扩展@Luiz 的答案 - 另一种很酷的方法是使用匿名函数:

function iterator($n, $cb)
{
    for($i=0; $i<$n; $i++) {
        call_user_func($cb, $i);
    }
}

$sum = 0;
iterator(10,
    function($i) use (&$sum)
    {
        $sum += $i;
    }
);

print $sum;
于 2011-12-17T18:16:41.803 回答
1

PHP 5.5 上现在存在同一个句子“yield”:

http://php.net/manual/en/language.generators.syntax.php

于 2013-08-11T10:07:48.397 回答
1

可能没有等价的运算符,但下面的代码在功能和开销上是等价的:

function file_lines($file) {
  static $fhandle;

  if ( is_null($fhandle) ) {
    $fhandle = fopen($file, 'r');

    if ( $fhandle === false ) {
      return false;
    }
  }

  if ( ($line = fgets($fhandle))!== false ) {
    return $line;
  }


  fclose($fhandle);
  $fhandle = null;
}

while ( $line = file_lines('some_file') ) {
  // ...
}

这看起来是对的。抱歉,我没有测试过。

于 2009-07-15T20:03:59.900 回答