php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76852 IteratorIterator doesn't initialize without being rewound
Submitted: 2018-09-08 22:04 UTC Modified: 2018-09-10 19:18 UTC
From: morozov at tut dot by Assigned:
Status: Not a bug Package: SPL related
PHP Version: 7.2.9 OS: Linux
Private report: No CVE-ID: None
 [2018-09-08 22:04 UTC] morozov at tut dot by
Description:
------------
Right after construction, the state of IteratorIterator doesn't reflect the state of the underlying iterator. Despite the fact that the underlying iterator is valid and has non-empty values of key and value, the wrapper is invalid and hass NULL values of key and value.

Test script:
---------------
$it = new ArrayIterator([1, 2, 3]);
var_dump($it->valid());
var_dump($it->key());
var_dump($it->current());

$it = new IteratorIterator($it);
var_dump($it->valid());
var_dump($it->key());
var_dump($it->current());


Expected result:
----------------
bool(true)
int(0)
int(1)
bool(true)
int(0)
int(1)


Actual result:
--------------
bool(true)
int(0)
int(1)
bool(false)
NULL
NULL


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-09-08 23:48 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2018-09-08 23:48 UTC] requinix@php.net
ArrayIterator may be usable immediately but that is not true for all iterators. IteratorIterator starts in an invalid state because the inner iterator may have as well.

Always call rewind() before using *any* iterator.
 [2018-09-10 19:18 UTC] morozov at tut dot by
Let's assume I have a component which instantiates the iterator and a few others which read data from it one by one. The readers, of course, cannot rewind it because it needs to remain in its current state, but why would the instantiator rewind a just created iterator?

> IteratorIterator starts in an invalid state because the inner iterator may have as well.

It's fine if it just reflects the state of the inner iterator, but if the inner iterator is valid, why is the wrapper not?

If the implementation just proxied all calls to the underlying iterator, like:
```
function valid()
{
   $this->innver->valid();
}
```

it wouldn't have this issue and would be the most simple implementation I can imagine. Why can't this be done?
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Apr 20 14:01:29 2024 UTC