标签: php-generators

PHP 生成器返回类型

我以前从未在 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 ,是否适合用于返回类型声明?

php iterator iterable generator php-generators

8
推荐指数
1
解决办法
2032
查看次数

使用php yield / Generator :: send()进行“数据输出流”

我知道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生成器进行顺序编写的“最佳实践”?

php php-generators

5
推荐指数
1
解决办法
694
查看次数

生成所有输入组合/排列的高效 PHP 算法

我正在尝试为多个输入计算数组中一组值的所有组合。类似于这个问题:

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)

php php-generators

2
推荐指数
1
解决办法
3972
查看次数

标签 统计

php ×3

php-generators ×3

generator ×1

iterable ×1

iterator ×1