PHP Exit, strange behavior

My colleague and I found very strange behavior using the new yield keyword in the PHP version: 5.5.11, and we want to know if the following is normal:

The code below is:

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 the function has a yield function, then: echo and die are completely skipped and not executed, but simply the yield assembly of the var_dumped object.

When we create an array / object manually and use return, it works the way it is intended.

We found that it even completely skips exceptions as soon as there is a way out in the function.

Is this really weird behavior, or did we find a mistake?

We cannot believe that this is necessary because it will significantly reduce the reliability of functions.

In addition, Google did not gouge any information related to this issue, so I thought I was asking here.

+6
source share
1 answer

Your var_dump simply outputs the generator object. No function was entered at this runtime. If you are actually executing with a generator, the function code 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); } 

output

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

or raises an exception if he comments on it.

+8
source

Source: https://habr.com/ru/post/969579/


All Articles