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:
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.
When we build the array/object manually and use return it works as it is intended.
We found out that it even total skips thrown exceptions once yield exists in the function.
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. 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"
or raises the exception if one comments it in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With