PHP递归迭代器的奇怪行为

PHP递归迭代器的奇怪行为,php,recursiveiterator,Php,Recursiveiterator,我发现PHP递归迭代器有一种非常奇怪的行为。如果子数组键不是从0开始的数字键,则它不会迭代子数组键。示例如下: class Foo{ private $id, $children; public function __construct($id, array $children = array()) { $this->id = $id; $this->children = $children; } public function getId()

我发现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

您的Baz类以$position=0开头。你期待什么?哦,谢谢你,我的眼睛呆滞了