Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: three plus zero?
(Example: nine)

The Note You're Voting On

jeroen at asystance dot nl
5 years ago
RocketInABog's seemingly trivial tIterator_array class has one huge problem (which just cost me a couple of hours).

Consider this example, using their class:
<?php
$values
= ['one', 'two', 'three'];
foreach (
$values as $v) {}
$current = current($values);
// $current === 'one', as you would expect

$iterator = new tIterator_array($values);
foreach (
$iterator as $v) {}
$current = $iterator->current(); // do NOT use current($iterator) or key($iterator)!!!
// $current === false, but why?
?>
The problem is that foreach resets arrays, but doesn't call Iterator::rewind on objects!

I also think it's a design mistake that foreach works with Iterator, but current(), key() and end() don't - these iterate over the objects fields.

I just refactored some code to use an Iterator instead of an array, and it broke in several very unexpected ways because of these differences.

<< Back to user notes page

To Top