[英]PHP8 - SplFixedArray iterator's next() doesn't move key pointer
請看一下這段代碼:
<?php
$array = new SplFixedArray(1);
print "\nKey1: " . $array->getIterator()->key();
$array->setSize(5);
$array->getIterator()->next();
$array->getIterator()->next();
$array->getIterator()->next();
print "\nKey2: " . $array->getIterator()->key() . "\n";
/*
Result (PHPv8.1.5):
Key1: 0
Key2: 0
*/
我是對的,在這種情況下,Key1 和 Key2 不應該相同 (0),而是從 0 (key1) 移動到 3 (key2)? 在使用 splFixedArray 的 PHP8 中,他們強制使用迭代器,因此它現在是嵌套循環安全的。 但是通過 ->next() 進行迭代似乎...不進行迭代。 所以指針仍然在 position 0。
是PHP8的bug還是我的代碼有誤?
謝謝你。
這不是 PHP 方面的任何錯誤。 它按預期工作。 問題出在您的代碼上。
$array->getIterator()
上面的行將始終返回迭代器的新實例。 它不遵循任何 singleton 模式每次都返回相同的實例。 因此,如果您希望使用迭代器移動內部指針並打印值,請將實例收集到一個變量中,並使用相同的變量每次調用next()
,如下所示:
<?php
$array = new SplFixedArray(1);
print "\nKey1: " . $array->getIterator()->key();
$array->setSize(5);
$it = $array->getIterator();
$it->next();
$it->next();
$it->next();
print "\nKey2: " . $it->key() . "\n";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.