10

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.

Steini
  • 2,753
  • 15
  • 24

1 Answers1

12

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.

Ulrich Thomas Gabor
  • 6,584
  • 4
  • 27
  • 41
  • Lol this is a tricky one. We tested everything but not that, the function was in use and thatswhy it seemed to be completely unlogical, however this is still strange its like a preprocessor and can make functions pretty unreliable that some code is skipped or executed when you dont really want it. Anyway thanks for your quick and correct feedback. – Steini May 20 '14 at 12:55
  • 1
    It is documented, by the way: http://www.php.net/manual/en/language.generators.syntax.php#language.generators.object – lonesomeday May 20 '14 at 12:56