从手册中查到的解释是:
Iterator extends Traversable {
/* Methods */
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 )
}
当一个实现了Iterator接口的对象,被foreach遍历时,会自动调用这些方法。调用的循序是:
rewind() -> valid() -> current() -> key() -> next()
下面来看一下简单的代码:
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";
}
以上会输出:
/Users/thanatos/Web/study/blean.php:15:string 'myIterator::rewind' (length=18)
/Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17)
/Users/thanatos/Web/study/blean.php:20:string 'myIterator::current' (length=19)
/Users/thanatos/Web/study/blean.php:25:string 'myIterator::key' (length=15)
/Users/thanatos/Web/study/blean.php:43:int 0
/Users/thanatos/Web/study/blean.php:43:string 'firstelement' (length=12)
---------------------------
/Users/thanatos/Web/study/blean.php:30:string 'myIterator::next' (length=16)
/Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17)
/Users/thanatos/Web/study/blean.php:20:string 'myIterator::current' (length=19)
/Users/thanatos/Web/study/blean.php:25:string 'myIterator::key' (length=15)
/Users/thanatos/Web/study/blean.php:43:int 1
/Users/thanatos/Web/study/blean.php:43:string 'secondelement' (length=13)
---------------------------
/Users/thanatos/Web/study/blean.php:30:string 'myIterator::next' (length=16)
/Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17)
/Users/thanatos/Web/study/blean.php:20:string 'myIterator::current' (length=19)
/Users/thanatos/Web/study/blean.php:25:string 'myIterator::key' (length=15)
/Users/thanatos/Web/study/blean.php:43:int 2
/Users/thanatos/Web/study/blean.php:43:string 'lastelement' (length=11)
---------------------------
/Users/thanatos/Web/study/blean.php:30:string 'myIterator::next' (length=16)
/Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17)