我试图更好地理解 PHP 中的迭代器。对于这个测试,我想制作一个项目树,并以不同的RecursiveIteratorIterator
模式列出它们。::SELF_FIRST 和 ::CHILD_FIRST 模式按我的预期工作。但是,当我想列出叶子时它不会。我在实现中一定缺少一些东西,它不允许该模式正常工作,因为它什么也没打印出来。我的Obj::hasChildren()
方法有问题吗?
这是测试类:
class Obj implements \RecursiveIterator {
public $children = array();
private $position;
private $name;
public function __construct($name)
{
$this->name = $name;
}
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 !empty($this->children[$this->position]);
}
public function getChildren()
{
return $this->children[$this->position];
}
public function __toString()
{
return $this->name;
}
}
这是测试:
use RecursiveIteratorIterator as RII;
$o1 = new Obj('Root');
$i1 = new Obj('Item 1');
$i12 = new Obj('Subitem 2');
$i1->children[] = new Obj('Subitem 1');
$i1->children[] = $i12;
$i12->children[] = new Obj('Subsubitem 1');
$i12->children[] = new Obj('Enough....');
$o1->children[] = $i1;
$o1->children[] = new Obj('Item 2');
$o1->children[] = new Obj('Item 3');
foreach (new RII($o1, RII::LEAVES_ONLY) as $o) {
echo "<br>" . $o;
}