duanfan9859 2012-06-20 12:39
浏览 40
已采纳

为什么PHP有迭代器对象?

I stumbled onto this PHP: Iterators page today and am wondering why these classes are even needed. I'd like to make the assumption that they serve a purpose, otherwise they wouldn't be in PHP. I'm struggling to see the benefit of such items when there are already very simple ways of doing these.

Is PHP making an error to be a more respectable/object oriented programming language? Or is there really a benefit to doing this?

A good example of how there's 2 ways of doing this was found in a PHP comment on the ArrayIterator:

<?php
$fruits = array(
    "apple" => "yummy",
    "orange" => "ah ya, nice",
    "grape" => "wow, I love it!",
    "plum" => "nah, not me"
);
$obj = new ArrayObject( $fruits );
$it = $obj->getIterator();

// How many items are we iterating over?
echo "Iterating over: " . $obj->count() . " values
";

// Iterate over the values in the ArrayObject:
while( $it->valid() ) {
    echo $it->key() . "=" . $it->current() . "
";
    $it->next();
}

// The good thing here is that it can be iterated with foreach loop

foreach ($it as $key=>$val)
echo $key.":".$val."
";

/* Outputs something like */

Iterating over: 4 values
apple=yummy
orange=ah ya, nice
grape=wow, I love it!
plum=nah, not me

?>
  • 写回答

4条回答 默认 最新

  • douhuai2015 2012-06-20 12:57
    关注

    Iterators are included in PHP because it lets you use common language constructs (such as foreach) with arbitrary objects, instead of being restricted to looping over built-in objects like arrays. It's a hassle (and breaks encapsulation) to force an object to transform it's internal state into an array for you to iterate over, and for large datasets can make your system run out of memory. An iterable lets you get past both of those issues by letting the object itself return individual elements only when requested.

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

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题