迭代器和迭代器的基类

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/>";
}

转载于:https://www.cnblogs.com/lilyhomexl/p/5604090.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值