Странное поведение рекурсивных итераторов PHP
Я обнаружил очень странное поведение рекурсивных итераторов PHP. Он не выполняет итерации по дочерним элементам, если ключи дочерних массивов не являются числовыми ключами, начиная с 0. Пример:
class Foo{
private $id, $children;
public function __construct($id, array $children = array()) {
$this->id = $id;
$this->children = $children;
}
public function getId() {
return $this->id;
}
public function hasChildren()
{
return count($this->children) > 0;
}
public function getChildren()
{
return $this->children;
}
}
class Baz implements RecursiveIterator {
private $position = 0, $children;
public function __construct(Foo $foo) {
$this->children = $foo->getChildren();
}
public function valid()
{
return isset($this->children[$this->position]);
}
public function next()
{
$this->position++;
}
public function current()
{
return $this->children[$this->position];
}
public function rewind()
{
$this->position = 0;
}
public function key()
{
return $this->position;
}
public function hasChildren()
{
return $this->current()->hasChildren();
}
public function getChildren()
{
return new Baz($this->current());
}
}
Следующее работает как ожидалось:
// Children array keys are numeric and starts from 0. It works.
$foo = new Foo(1, array(
new Foo(2,
array(new Foo(3)))
));
foreach(new RecursiveIteratorIterator(new Baz($foo), RecursiveIteratorIterator::SELF_FIRST) as $j) {
var_dump($j->getId());
}
Выходы:
int 2
int 3
Теперь тот же код, но дочерние ключи начинаются с 2:
// Now array keys starts from 2 and it does not work.
$foo = new Foo(1, array(
2 => new Foo(2,
array(3 => new Foo(3)))
));
foreach(new RecursiveIteratorIterator(new Baz($foo), RecursiveIteratorIterator::SELF_FIRST) as $j) {
var_dump($j->getId());
}
Выход пуст.
Это ошибка или что? Версия PHP 5.3.27/Windows x86