Bug #79511 [Nab]: Return is silently ignored with yield even if yield is never reached
| From: | cmb@php.net | Date: | Thu, 23 Apr 2020 09:24:03 +0000 |
| Subject: | Bug #79511 [Nab]: Return is silently ignored with yield even if yield is never reached | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-226737@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=79511&edit=1
ID: 79511
Updated by: cmb@php.net
Reported by: michael dot vorisek at email dot cz
Summary: Return is silently ignored with yield even if yield
is never reached
Status: Not a bug
Type: Bug
Package: Scripting Engine problem
Operating System: any
PHP Version: 7.4.5
Assigned To: cmb
Block user comment: N
Private report: N
New Comment:
In this case, Cl::__get() is a normal function, not a generator
function. The anonymous function inside of Cl::__get() is a
generator function, though.
Previous Comments:
------------------------------------------------------------------------
[2020-04-23 09:12:17] michael dot vorisek at email dot cz
Ok, just example how to mix non-generator and generator return.
class Cl {
public function __get($name) {
if ($name === 'gen') {
return (fn() => yield 'a')(); // return generator
} else {
return ['b']; // return array
}
}
}
$cl = new Cl();
var_dump($cl->gen);
var_dump(iterator_to_array($cl->gen));
var_dump($cl->not_gen);
------------------------------------------------------------------------
[2020-04-23 08:50:35] nikic@php.net
Why would that be disallowed? It's equivalent to
function() {
return yield 5;
}
which is not terribly useful, but perfectly legal code. It yields one value, accepts one value and
specifies the accepted value as the coroutine return value.
------------------------------------------------------------------------
[2020-04-23 08:41:00] michael dot vorisek at email dot cz
This should then be - like return - not allowed, shouldn't?
$u = fn() => yield 5;
echo $u();
------------------------------------------------------------------------
[2020-04-23 08:25:33] nikic@php.net
Any function containing yield is a generator and follows generator semantics. Whether the yield
actually gets executed does not matter.
Please, this is generators 101.
------------------------------------------------------------------------
[2020-04-23 08:20:55] michael dot vorisek at email dot cz
But the 2nd example does not call yield at all - if (false) {} pattern is used a lot to comment code
to keep it refactorable - why is this allowed and where is this behaviour defined?
------------------------------------------------------------------------
The remainder of the comments for this report are too long. To view
the rest of the comments, please view the bug report online at
https://bugs.php.net/bug.php?id=79511
--
Edit this bug report at https://bugs.php.net/bug.php?id=79511&edit=1