本篇文章分享的内容是【php预定义接口】迭代器,现在分享给大家,有需要的朋友可以参考一下本篇文章的内容
iterator(迭代器)接口
简介 :可在内部迭代自己的外部迭代器或类的接口。
具体作用解释
接口摘要 :
iterator extends traversable {    /* 方法 */
    abstract public mixed current ( void )    abstract public scalar key ( void )    abstract public void next ( void )    abstract public void rewind ( void )    abstract public bool valid ( void )
}
范例:
example #1 基本用法(使用 foreach 时,迭代器方法的调用顺序)<?phpclass myiterator implements iterator {
    private $position = 0;    private $array = array(        "firstelement",        "secondelement",        "lastelement",
    );  
    public function __construct() {
        $this->position = 0;
    }    function rewind() {
        var_dump(__method__);        $this->position = 0;
    }    function current() {
        var_dump(__method__);        return $this->array[$this->position];
    }    function key() {
        var_dump(__method__);        return $this->position;
    }    function next() {
        var_dump(__method__);
        ++$this->position;
    }    function valid() {
        var_dump(__method__);        return isset($this->array[$this->position]);
    }
}$it = new myiterator;foreach($it as $key => $value) {
    var_dump($key, $value);    echo "\n";
}1.rewind -> valid -> current -> key 
2.next -> valid -> current -> key3.next -> valid -> current -> key4.next -> valid?>
iterator(迭代器)接口
简介 :可在内部迭代自己的外部迭代器或类的接口。
具体作用解释
接口摘要 :
iterator extends traversable {    /* 方法 */
    abstract public mixed current ( void )    abstract public scalar key ( void )    abstract public void next ( void )    abstract public void rewind ( void )    abstract public bool valid ( void )
}
范例:
example #1 基本用法(使用 foreach 时,迭代器方法的调用顺序)<?phpclass myiterator implements iterator {
    private $position = 0;    private $array = array(        "firstelement",        "secondelement",        "lastelement",
    );  
    public function __construct() {
        $this->position = 0;
    }    function rewind() {
        var_dump(__method__);        $this->position = 0;
    }    function current() {
        var_dump(__method__);        return $this->array[$this->position];
    }    function key() {
        var_dump(__method__);        return $this->position;
    }    function next() {
        var_dump(__method__);
        ++$this->position;
    }    function valid() {
        var_dump(__method__);        return isset($this->array[$this->position]);
    }
}$it = new myiterator;foreach($it as $key => $value) {
    var_dump($key, $value);    echo "\n";
}1.rewind -> valid -> current -> key 
2.next -> valid -> current -> key3.next -> valid -> current -> key4.next -> valid?>
相关推荐:
php预定义变量详解
php预定义变量方法
以上就是【php预定义接口】迭代器的详细内容。
   
 
   