人们可能期望 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()。
在 php 5.6.30 & 7.1.2 上测试,结果完全相同。