我以前从未在 PHP 中使用过生成器,文档中也没有显示返回类型声明的示例。
在 PhpStorm 中,执行此操作时 IDE 中出现错误:
public function getDataIncrementally(): void {
yield from [/* some large set of numbers*/];
}
Run Code Online (Sandbox Code Playgroud)
错误是:
生成器只能声明返回类型为 Generator、Iterator 或 Traversable,或可迭代,不允许使用 void。
我可以看到继承树是Traversable-> Iterator-> Generator。同时,iterable是 PHP 7.1 中引入的一种新的伪类型。
iterable如果我只需要支持 PHP >= 7.1 ,是否适合用于返回类型声明?
我知道yield可以用于创建数据迭代器,例如从CSV文件读取数据。
function csv_generator($file) {
$handle = fopen($file,"r");
while (!feof($handle)) {
yield fgetcsv($file);
}
fclose($file);
}
Run Code Online (Sandbox Code Playgroud)
但是Generator :: send()方法建议我可以对顺序写入而不是读取进行相同的操作。
例如,我想使用这样的东西:
function csv_output_generator($file) {
$handle = fopen('file.csv', 'w');
while (null !== $row = yield) {
fputcsv($handle, $row);
}
fclose($handle);
}
$output_generator = csv_output_generator($file);
$output_generator->send($rows[0]);
$output_generator->send($rows[1]);
$output_generator->send($rows[2]);
// Close the output generator.
$output_generator->send(null);
Run Code Online (Sandbox Code Playgroud)
我认为以上方法会起作用。
但是$output_generator->send(null);对于关闭似乎是错误的,还是不理想的。这意味着我永远无法发送原义的null。可以用csv编写,但是也许有一个发送null的用例。
是否有使用PHP生成器进行顺序编写的“最佳实践”?
我正在尝试为多个输入计算数组中一组值的所有组合。类似于这个问题:
例如:
function sampling($chars, $size, $combinations = array()) {
if (empty($combinations)) {
$combinations = $chars;
}
if ($size == 1) {
return $combinations;
}
$new_combinations = array();
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
return sampling($chars, $size - 1, $new_combinations);
}
$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);
echo implode($output,', ');
Run Code Online (Sandbox Code Playgroud)
输出:
aa, ab, ac, ba, bb, bc, ca, cb, cc
Run Code Online (Sandbox Code Playgroud)
但问题是当我把它提升到一个更大的列表时,例如:
$chars = array('a', 'b', …Run Code Online (Sandbox Code Playgroud)