从存储中分离当前条目会阻止 SplObjectStorage::next() 操作。
作为 PHPUnit 测试的示例
<?php
public function testDetachingCurrentPreventsNext()
{
$storage = new SplObjectStorage;
$storage->attach(new stdClass);
$storage->attach(new stdClass);
$storage->rewind();
$iterated = 0;
$expected = $storage->count();
while ($storage->valid()) {
$iterated++;
$storage->detach($storage->current());
$storage->next();
}
$this->assertEquals($expected, $iterated);
}
?>
此测试将失败,因为迭代将永远无法到达第二个 stdClass。
SplObjectStorage::next() 显然依赖于当前元素有效。
如果要分离迭代期间的对象,您应该取消引用对象,然后调用 next(),并在 next() 后分离引用。
<?php
public function testDetachingReferenceAfterNext()
{
$storage = new SplObjectStorage;
$storage->attach(new stdClass);
$storage->attach(new stdClass);
$storage->rewind();
$iterated = 0;
$expected = $storage->count();
while ($storage->valid()) {
$iterated++;
$object = $storage->current();
$storage->next();
$storage->detach($object);
}
$this->assertEquals($expected, $iterated);
}
?>
此测试将通过。