Bug #79511 [Com]: Return is silently ignored with yield even if yield is never reached

From: Date: Thu, 23 Apr 2020 09:12:17 +0000
Subject: Bug #79511 [Com]: 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-226734@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 Comment by: michael dot vorisek at email dot cz 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: 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); Previous Comments: ------------------------------------------------------------------------ [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? ------------------------------------------------------------------------ [2020-04-23 07:16:41] cmb@php.net No, the return is not ignored; it just has special semantics in generator functions; see <https://3v4l.org/rCAX4> and <https://github.com/php/php-langspec/blob/master/spec/14-classes.md#class-generator>. ------------------------------------------------------------------------ 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

« previous php.bugs (#226734) next »