PHP递归迭代器的奇怪行为

时间:2014-02-10 04:40:53

标签: 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() {
    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());
}

输出为空。

是bug还是什么? PHP版本是5.3.27 / Windows x86

0 个答案:

没有答案