【问题标题】:What is the use of "yield" in an expression context?在表达式上下文中“yield”的用途是什么?
【发布时间】:2013-10-16 06:16:42
【问题描述】:

如 php 手册中的 yield 可以使用表达式的一部分。 $data = (yield $value);但它没有为 $myval 分配任何东西。我在这里做错了吗?我们如何在表达式中使用它?

     function test_yield(){
        for ($i=0; $i <10; $i++) { 
             $myval = (yield $i);
             echo " \ ".$myval." / <br />";
        }

    }
    foreach (test_yield() as $value) {
        echo $value;
    }

【问题讨论】:

    标签: php generator yield


    【解决方案1】:

    来自 PHP rfc:generators

    yield 表达式的返回值是使用send() 发送到生成器的任何值。如果没有发送任何内容(例如在 foreach 迭代期间),则返回 null。

    你的foreach 代码永远不会在send()s 中进入生成器,所以yield 总是返回null。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-28
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      • 2018-07-29
      • 2013-04-18
      • 2018-04-26
      相关资源
      最近更新 更多