迭代器和迭代器的基类

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

posted @ 2016-06-21 16:30  青柠檬lily  阅读(180)  评论(0编辑  收藏  举报