php-src/ext/spl/tests/SplFixedArray_override_getIterator.phpt
Alex Dowad 4222ae16e7 SplFixedArray is Aggregate, not Iterable
One strange feature of SplFixedArray was that it could not be used in nested foreach
loops. If one did so, the inner loop would overwrite the iteration state of the outer
loop.

To illustrate:

    $spl = SplFixedArray::fromArray([0, 1]);
    foreach ($spl as $a) {
      foreach ($spl as $b) {
        echo "$a $b";
      }
    }

Would only print two lines:

    0 0
    0 1

Use the new InternalIterator feature which was introduced in ff19ec2df3 to convert
SplFixedArray to an Aggregate rather than Iterable. As a bonus, we get to trim down
some ugly code! Yay!
2020-09-23 08:33:24 +02:00

46 lines
834 B
PHP

--TEST--
SPL: FixedArray: overriding getIterator()
--FILE--
<?php
class A extends SplFixedArray
{
public function getIterator(): Iterator
{
$iterator = parent::getIterator();
while ($iterator->valid()) {
echo "In A: key={$iterator->key()} value={$iterator->current()}\n";
yield $iterator->key() => $iterator->current();
$iterator->next();
}
}
}
echo "==SplFixedArray instance==\n";
$a = new SplFixedArray(3);
$a[0] = "a";
$a[1] = "b";
$a[2] = "c";
foreach ($a as $k => $v) {
echo "$k => $v\n";
}
echo "==Subclass instance==\n";
$a = new A(3);
$a[0] = "d";
$a[1] = "e";
$a[2] = "f";
foreach ($a as $k => $v) {
echo "$k => $v\n";
}
--EXPECT--
==SplFixedArray instance==
0 => a
1 => b
2 => c
==Subclass instance==
In A: key=0 value=d
0 => d
In A: key=1 value=e
1 => e
In A: key=2 value=f
2 => f