Yasuo Ohgaki wrote on 21/01/2015 02:48:
I don't think that's an either/or situation: in most cases, it
would be up to the user to create that independent iterator,
because there's no general algorithm for cloning one that the
engine could use. (Think of an iterator proxying a database
cursor, for instance - it could be rewindable directly, but
cloning it would imply issuing a new query to create a new cursor
with separate state.) So the engine needs to issue an error
telling the user that they're reusing an object in an dangerous
way. An extended interface could be created later for those cases
that can handle the situation, although I doubt it would be that
common a use case.
I think if users need nested database cursor based iterator or like,
they should create new iterator object by themselves.
i.e. User should have __clone() that opens new cursor.
I agree, and that's why I think nesting should be disabled by default.
It needs to be a run-time flag, as nesting could be arbitrarily indirect:
function iterator_dump($iter) {
foreach ( $iter as $x ) {
var_dump($x);
}
}
foreach ( $some_iterator as $foo ) {
dump ( $foo );
iterator_dump( $some_iterator ); // ERROR: Iterator cannot be used
within nested foreach loops.
iterator_dump( clone $some_iterator ); // OK, up to creator of
iterator to implement __clone()
}
Perhaps foreach ( $some_iterator as $foo ) { ... } should be translated
something like this:
- if check_foreach_flag( $some_iterator ) == 1 then raise error
- set_foreach_flag( $some_iterator )
- if check_initialised( $some_iterator ) then $some_iterator->rewind()
- (if rewind fails, raise error)
--- perform loop until iterator exhausted or break statement encountered ---
- clear_foreach_flag( $some_iterator )
Where check_initialised() is some way of checking if the iterator has
emitted values somewhere else, so needs rewinding. Without that, you
couldn't use foreach on any iterator that couldn't be rewound, which
would be pretty useless.
I've no idea how feasible such flags are in the current implementation,
though.
Regards,
--
Rowan Collins
[IMSoP]