Pythonの収量演算子と同等のPHP
-
16-09-2019 - |
質問
のPython(およびその他)では、増分関数で「収率」演算子を使用して大量のデータを処理することができます。どのようなPHPでこれを行うには、同様の方法だろうか?
たとえば、私は潜在的に非常に大きなファイルを読みたいと思った場合、それは基本的には」と同じものであるように(この例では、不自然であるように、私は一度に各ライン1に仕事ができる、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の文と一緒に機能を使用したい場合は、しかし、良いオプションがあります
に。彼らは、Pythonのジェネレータと非常によく似て何かを達成するために使用することができます。他のヒント
https://wiki.php.net/rfc/generators のでRFCがありますPHP 5.5に含まれる可能性があるだけで、ことadressingます。
平均時間では、この概念実証のユーザランドで実装貧しいマン「ジェネレータ関数」のをチェックしてください。
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";
私は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
は、コールバック関数に渡され、あなたがやりたいことができます。
@ルイスの答えを拡張する - 別のクールな方法は、無名関数を使用することです。
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に今存在してます: