|  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
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please — but make sure to vote on the bug!
Your email address:
Solve the problem:
38 + 47 = ?
Subscribe to this entry?

 [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-2023 The PHP Group
All rights reserved.
Last updated: Mon Dec 04 23:01:27 2023 UTC