php.net |  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
Votes:2
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
Have you experienced this issue?
Rate the importance of this bug to you:

 [2018-01-15 17:43 UTC] php at fleshgrinder dot com
Description:
------------
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: https://3v4l.org/v0qAZ
Generator code: https://3v4l.org/2E7EJ

Also, note that HHVM/Hack behaves as expected.

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

var_dump($it->valid());

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

Expected result:
----------------
bool(false)

Actual result:
--------------
bool(false)

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.

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

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: Tue Apr 23 18:01:34 2024 UTC