人们可能期望 SplDoublyLinkedList::shift 能正确维护内部指针,但事实并非如此,即使您先回绕,它也不会产生任何结果。
<?php
while ($splDoublyLinkedList->valid()) {
yield $splDoublyLinkedList->shift();
}
?>
这可能是设计使然,但以下情况引发更多疑问
<?php
$test = new \SplDoublyLinkedList;
$dataSet = [
['id' => 1],
['id' => 2],
['id' => 3],
['id' => 4],
];
foreach ($dataSet as $row) {
$test->push($row);
}
echo "count: " . $test->count() . PHP_EOL;
echo "valid: " . ($test->valid() ? 'true' : 'false') . PHP_EOL;
echo "current: " . var_export($test->current(), true) . PHP_EOL;
echo "key: " . $test->key() . PHP_EOL;
echo "1st shift: " . var_export($test->shift(), true) . PHP_EOL;
echo "count: " . $test->count() . PHP_EOL;
echo "valid: " . ($test->valid() ? 'true' : 'false') . PHP_EOL;
echo "current: " . var_export($test->current(), true) . PHP_EOL;
echo "key: " . $test->key() . PHP_EOL;
echo "2nd shift: " . var_export($test->shift(), true) . PHP_EOL;
echo "count: " . $test->count() . PHP_EOL;
echo "valid: " . ($test->valid() ? 'true' : 'false') . PHP_EOL;
echo "current: " . var_export($test->current(), true) . PHP_EOL;
echo "key: " . $test->key() . PHP_EOL;
echo "rewinding... " . PHP_EOL;
$test->rewind();
echo "current: " . var_export($test->current(), true) . PHP_EOL;
echo "2nd shift: " . var_export($test->shift(), true) . PHP_EOL;
echo "count: " . $test->count() . PHP_EOL;
echo "valid: " . ($test->valid() ? 'true' : 'false') . PHP_EOL;
echo "current: " . var_export($test->current(), true) . PHP_EOL;
echo "key: " . $test->key() . PHP_EOL;
?>
将产生以下结果
<?php
?>
结论:我可能遗漏了 SplDoublyLinkedList::shift 为什么首先没有维护正确的内部索引的原因,但我发现即使能够最终得到一个有效的 valid() 和一个有效的 key(),却没有 current(),而显然存在一个 current(),这更令人困惑。
在 php 5.6.30 和 7.1.2 上测试,结果完全相同。