douchuoxuan3177 2010-03-16 23:34
浏览 63
已采纳

为什么我必须回放IteratorIterator

$arrayIter = new ArrayIterator( array(1, 2) );
$iterIter = new IteratorIterator($arrayIter);

var_dump($iterIter->valid()); //false
var_dump($arrayIter->valid()); //true

If I first call $iterIter->rewind(), then $iterIter->valid() is true. I'm curious why it requires that rewind() be called. I imagine there's good reason for it, but I would have expected it to simply start iteration at whatever state it's inner iterator is in, and leave it as an option to rewind before beginning iteration.

calling next() also seems to put it in a "valid" state(although it advances to the next position, suggesting it was previously at the first position).

$arrayIter = new ArrayIterator(array(1,2));
$iterIter = new IteratorIterator($arrayIter);

$iterIter->next();
var_dump($iterIter->valid()); 

Again, I'm curious why I need to call rewind(), despite the inner iterator being in a valid state.

  • 写回答

3条回答 默认 最新

  • dongxiangxie8181 2010-03-16 23:38
    关注

    With a fresh iterator the position isn't initialized, simply for performance reason, you can stack iterators on top of other iterators, if all of them would rewind during construction there would be some performance impact, additionally some iterators might change their first value after the constructor was executed - which is unknown to iterators further out.

    Iterators are usually executed by foreach() which does a rewind() first ...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题