简体   繁体   English

PHP收益,奇怪的行为

[英]PHP Yield, strange behaviour

me and a colleague found a very strange behaviour using the new keyword "yield" in PHP version: 5.5.11 and we want to know if the following is normal: 我和一位同事在PHP版本:5.5.11中使用新关键字“yield”发现了一个非常奇怪的行为,我们想知道以下是否正常:

Given is the following code: 给出以下代码:

function yieldTest()
{
    echo 'wtf1';
    die('wtf2');

    foreach (['foo', 'bar', 'baz'] as $each) {
        yield $each;
    }
}

var_dump(yieldTest()); 

The curious thing about this is that if "yield" exists in the function, both: echo and die is totally skipped and not executed and merely the object "yield" builds is var_dumped. 关于这一点的奇怪之处在于,如果函数中存在“yield”,则:echo和die完全被跳过并且不被执行,并且仅对象“yield”构建是var_dumped。

When we build the array/object manually and use return it works as it is intended. 当我们手动构建数组/对象并使用return时,它按预期工作。

We found out that it even total skips thrown exceptions once yield exists in the function. 我们发现,一旦函数中存在yield,它甚至会跳过抛出异常。

Is this very strange behaviour really intended or did we find a bug? 这种非常奇怪的行为是真的意图还是我们发现了一个错误?

We cannot really belive that this is wanted because it would drastically reduce the reliability of functions. 我们不能真正相信这是需要的,因为它会大大降低功能的可靠性。

Also Google did not puke out any information related to this problem, thatswhy I thought I ask here. 谷歌也没有找到任何与此问题有关的信息,为什么我认为我在这里问。

Your var_dump just outputs a generator object. 你的var_dump只输出一个生成器对象。 At this time of execution the function has not been entered. 在此时执行该功能尚未输入。 If you proceed in actually using the generator, the code of the function is executed: 如果继续实际使用生成器,则执行函数的代码:

function yieldTest() {
    echo 'wtf1';
    //throw Exception('test');

    foreach (['foo', 'bar', 'baz'] as $each) {
        yield $each;
    }
}

$test = yieldTest();
foreach ($test as $k) {
  var_dump($k);
}

outputting 输出

wtf1string(3) "foo" string(3) "bar" string(3) "baz" wtf1string(3)“foo”string(3)“bar”string(3)“baz”

or raises the exception if one comments it in. 如果有人评论,则提出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM