PHP

PHP迭代器-例

2018-01-12  本文已影响5人  保儿洁

代码

class Test implements Iterator{
    private $item = array('id'=>1,'name'=>'php');

    //指针重置
    public function rewind(){
        reset($this->item);
    }

    //当前指针值
    public function current(){
        return current($this->item);
    }

    //当前指针键名
    public function key(){
        return key($this->item);
    }

    //指针后移
    public function next(){
        return next($this->item);
    }

    //当前指针是否为空
    public function valid(){
        return($this->current()!==false);
    }
}
//测试
$t=new Test;
foreach($t as $k=>$v){
    echo$k,'--->',$v,"\n";
}

Out

id--->1
name--->php
上一篇下一篇

猜你喜欢

热点阅读