|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75819 Generators have different behavior than Iterators
Submitted: 2018-01-15 17:43 UTC Modified: 2018-01-21 14:43 UTC
Avg. Score:4.0 ± 0.0
Reproduced:2 of 2 (100.0%)
Same Version:2 (100.0%)
Same OS:1 (50.0%)
From: php at fleshgrinder dot com Assigned:
Status: Open Package: Class/Object related
PHP Version: 7.2.1 OS: -
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
Block user comment
Status: Assign to:
Bug Type:
From: php at fleshgrinder dot com
New email:
PHP Version: OS:


 [2018-01-15 17:43 UTC] php at fleshgrinder dot com
Generators behave differently than Iterators when calling valid on them followed by a loop. A non-rewindable iterator can be asked if it is valid by calling valid on it followed by a loop. The same is not possible with a Generator because it throws an exception stating that an already closed generator cannot be iterated.

This is extremely hard to debug because the problem is not apparent at all to the reader of the code.

Iterator code:
Generator code:

Also, note that HHVM/Hack behaves as expected.

Test script:
$it = (function () { if (false) { yield 'foo'; }})();


foreach ($it as $k => $v) { var_dump($k, $v); }

Expected result:

Actual result:

Fatal error: Uncaught Exception: Cannot traverse an already closed generator in /in/2E7EJ:7
Stack trace:
#0 {main}
  thrown in /in/2E7EJ on line 7

Process exited with code 255.


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2018-01-21 14:43 UTC] php at fleshgrinder dot com
Note that this behavior can be observed only if the Generator is empty, like in the examples.
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Jul 17 11:01:28 2024 UTC