人們可能會預期 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 上測試,結果完全相同。