在Python中(以及其他)时,可以递增地通过在功能使用“成品率”操作处理大量的数据。什么是在PHP这样做类似的方式?

举例来说,可以说在Python,如果我想读一个潜在的非常大的文件,我可以在同一时间在每行一个工作像这样(这个例子是人为的,因为它基本上是同样的事情,“对在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)是我使用的是私有实例变量来跟踪状态,每个函数被调用时采取相应的行动,但似乎必须有一个更好的办法。

有帮助吗?

解决方案

PHP有直接的等效称为发电机的。

<强>旧(预PHP 5.5回答):

不幸的是,不是一种语言等效。最简单的办法就是要么你已经做了什么,或创建一个使用实例变量保持状态的对象。

然而有一个很好的选择,如果你想使用的功能与在foreach语句一起: SPL迭代器。它们可以被用来实现神似蟒蛇发电机的东西。

其他提示

有在 https://wiki.php.net/rfc/generators 一个RFC adressing只是,这可能会被包含在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";

我在Python实现在任何其它语言,包括PHP前原型的一切。我结束了使用回调来实现我会与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传递给回调函数,你可以做你想做的。

扩展@路易斯的回答 - 另一个很酷的方法是使用匿名函数:

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;

有可能不是等效的操作,但下面的代码是在功能和开销当量:

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') ) {
  // ...
}

这看起来是正确的。对不起,我还没有测试它。

在相同的句子 '成品率' 现在PHP 5.5存在:

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top