php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #76104 Generator::next() causes yield to return null
Submitted: 2018-03-16 06:44 UTC Modified: 2018-03-16 17:34 UTC
From: alexey at kopytko dot com Assigned: cmb (profile)
Status: Closed Package: Scripting Engine problem
PHP Version: 7.2.3 OS:
Private report: No CVE-ID: None
 [2018-03-16 06:44 UTC] 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

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-03-16 07:10 UTC] requinix@php.net
-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
 [2018-03-16 07:10 UTC] requinix@php.net
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.
 [2018-03-16 17:33 UTC] cmb@php.net
Automatic comment from SVN on behalf of cmb
Revision: http://svn.php.net/viewvc/?view=revision&amp;revision=344528
Log: Fix #76104: Generator::next() causes yield to return null
 [2018-03-16 17:34 UTC] cmb@php.net
-Status: Verified +Status: Closed -Assigned To: +Assigned To: cmb
 [2018-03-16 17:34 UTC] cmb@php.net
This bug has been fixed in the documentation's XML sources. Since the
online and downloadable versions of the documentation need some time
to get updated, we would like to ask you to be a bit patient.

Thank you for the report, and for helping us make our documentation better.
 [2020-02-07 06:05 UTC] phpdocbot@php.net
Automatic comment on behalf of cmb
Revision: http://git.php.net/?p=doc/en.git;a=commit;h=9fadd7d16abead86b784e00ca902314ce723abd7
Log: Fix #76104: Generator::next() causes yield to return null
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Mon Nov 25 22:01:31 2024 UTC