Bug #77587 [Opn->Nab]: Inconsistent behaviour when returning generators
| From: | nikic@php.net | Date: | Fri, 08 Feb 2019 12:07:53 +0000 |
| Subject: | Bug #77587 [Opn->Nab]: Inconsistent behaviour when returning generators | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-219439@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=77587&edit=1
ID: 77587
Updated by: nikic@php.net
Reported by: adamnicholson10 at gmail dot com
Summary: Inconsistent behaviour when returning generators
-Status: Open
+Status: Not a bug
Type: Bug
Package: *General Issues
Operating System: Linux
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
return foo() is just that: You are returning a generator object.
What you are looking for is "yield from foo()". See also http://php.net/manual/en/language.generators.syntax.php#control-structures.yield.from
Previous Comments:
------------------------------------------------------------------------
[2019-02-08 12:03:57] adamnicholson10 at gmail dot com
Description:
------------
There appears to be inconsistent behaviour when returning generators.
Given the function
foo() returns a generator, when you consume that generator in a new
function which also returns a generator, you would expect return foo() to have the same
behaviour as looping over the values of foo() and performing a yield on
each value; however this doesn't appear to be the case if the function you are consuming
foo() contains other yield statements.
It looks like PHP is getting confused by having both yield statements, and return
$generator statements, in the same function body.
This appears to affect all PHP versions tested which support generators
POC (code below): https://3v4l.org/e86mK
Test script:
---------------
<?php
function generator() {
foreach ([1, 2, 3, 4, 5] as $i) {
yield $i;
}
}
function A(): \Generator {
return generator();
}
function B(): \Generator {
if (false) {
yield 7;
return;
}
return generator();
}
function C(): \Generator {
if (false) {
yield 7;
return;
}
foreach (generator() as $i) {
yield $i;
}
}
echo "-A\n";
foreach (A() as $i) {
echo "{$i}\n";
}
echo "-B\n";
foreach (B() as $i) {
echo "{$i}\n";
}
echo "-C\n";
foreach (C() as $i) {
echo "{$i}\n";
}
echo "Done\n";
Expected result:
----------------
-A
1
2
3
4
5
-B
1
2
3
4
5
-C
1
2
3
4
5
Done
Actual result:
--------------
-A
1
2
3
4
5
-B
-C
1
2
3
4
5
Done
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=77587&edit=1