Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 819
Steini Avatar asked May 20 '14 12:05

Steini


1 Answers

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.

like image 125
Ulrich Thomas Gabor Avatar answered Sep 21 '22 10:09

Ulrich Thomas Gabor