首页 > PHP教程 > PHP预定义接口的使用

PHP Iterator(迭代器)接口

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 boolean valid ( void )

}

 

让一个类实现一个基本的迭代功能

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

PHP历史版本

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。