首页 > 其他 > 详细

迭代器和迭代器的基类

时间:2016-06-21 17:43:12      阅读:289      评论:0      收藏:0      [点我收藏+]

Iterator 迭代器

IteratorAggregate接口

//迭代器和迭代器的示例基类
class ObjectIterator implements Iterator {
    private $obj;
    private $count;
    private $currentIndex;
    function __construct($obj) {
        $this->obj = $obj;
        $this->count = count($this->obj->data);
    }
    function rewind() {//内部数据指针设置回数据开始处
        $this->currentIndex = 0;
    }
    function valid() {//判断数据指针的当前位置是否还存在更多数据
        return $this->currentIndex < $this->count;
    }
    function key() {//函数将返回数据指针的值
        return $this->currentIndex;
    }
    function current() {//返回保存在当前数据指针的值
        return $this->obj->data[$this->currentIndex];
    }
    function next() {//函数在数据中移动数据指针的位置
        $this->currentIndex++;
    }
}
class Object implements IteratorAggregate {
    public $data = array();
    function __construct($in) {
        $this->data = $in;
    }
    function getIterator() {
        return new ObjectIterator($this);
    }
}
$myObject = new object(array(2,4,6,8,10));
$myIterator = $myObject->getIterator();
for($myIterator->rewind();$myIterator->valid();$myIterator->next()) {
    $key = $myIterator->key();
    $value = $myIterator->current();
    echo $key."=>".$value."<br/>";
}

迭代器和迭代器的基类

原文:http://www.cnblogs.com/lilyhomexl/p/5604090.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!