|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2020-04-23 00:38 UTC] michael dot vorisek at email dot cz
Description:
------------
See test script
Test script:
---------------
function x(): iterable {
yield 'a';
return ['b']; // silently ignored!
}
function y(): iterable {
if (false) {
yield 'c';
}
return ['d']; // not returned at all - yield above needs to be commented out even if the condition is never matched!
}
foreach (x() as $v) {echo $v."\n";}
echo "\n";
foreach (y() as $v) {echo $v."\n";}
Expected result:
----------------
a
b
d
Actual result:
--------------
a
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Nov 16 12:00:01 2025 UTC |
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?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.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);