收益率不返回值

时间:2016-06-04 12:09:45

标签: php yield

我正在尝试调整此代码:

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        echo implode($perms); // yield (implode($perms));
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}

收益率,如您所见,在同一行中评论。但这样做不会返回任何值。

我打电话给:

  foreach (pc_permute($a) as $y) {
        echo $y;
  }

$ a应该是$a = [0,1,2];

使用echo工作而不是yield。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的递归调用会忽略生成的值。

从PHP 7开始,您可以使用generator delegationself):

yield from

对于旧版本,只需编写一个产生每个结果的循环。

相关问题