Bug->Doc #76104 [Opn->Ver]: Generator::next() causes yield to return null
| From: | requinix@php.net | Date: | Fri, 16 Mar 2018 07:10:12 +0000 |
| Subject: | Bug->Doc #76104 [Opn->Ver]: Generator::next() causes yield to return null | ||
| References: | 1 | Groups: | php.doc.bugs |
| Request: | Send a blank email to doc-bugs+get-15535@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=76104&edit=1
ID: 76104
Updated by: requinix@php.net
Reported by: alexey at kopytko dot com
-Summary: foreach over a generator with an intermit send()
works unexpectedly
+Summary: Generator::next() causes yield to return null
-Status: Open
+Status: Verified
-Type: Bug
+Type: Documentation Problem
Package: Scripting Engine problem
PHP Version: 7.2.3
Block user comment: N
Private report: N
New Comment:
next() and send() both advance the generator. That's how generators work. Using next(),
explicitly or implicitly, means there's no way to pass a value back through the yield and thus
the code will get null - just like when trying to get the return value from a function that
doesn't return anything.
Previous Comments:
------------------------------------------------------------------------
[2018-03-16 06:44:11] alexey at kopytko dot com
Description:
------------
foreach calls next() on a generator, which for some reason triggers send(null) on the generator.
All previous versions are also affected:
https://3v4l.org/bfg64#v560
First reported here:
https://stackoverflow.com/q/37817315
Test script:
---------------
$generator = (function () {
for ($i = 0; $i < 5; $i += 1) {
$answer = (yield $i * 2);
echo "received: $answer\n";
}
})();
foreach ($generator as $x) {
echo "sending $x\n";
$generator->send($x);
}
Expected result:
----------------
sending 0
received: 0
sending 2
received: 2
sending 4
received: 4
sending 6
received: 6
sending 8
received: 8
Actual result:
--------------
sending 0
received: 0
received:
sending 4
received: 4
received:
sending 8
received: 8
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=76104&edit=1