Iterator (interface)
Iterator接口
介绍
(PHP 5 >= 5.0.0, PHP 7)
外部迭代器或可以在内部迭代的对象的接口。
界面简介
迭代器
扩展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 )
}
预定义的迭代器
PHP 已经为许多日常任务提供了许多迭代器。请参阅 SPL迭代器以获取列表。
例子
示例#1 基本用法
这个例子演示了在迭代器中使用 foreach 时调用哪些方法。
<?php
class myIterator implements Iterator {
private $position = 0;
private $array = array(
"firstelement",
"secondelement",
"lastelement",
public function __construct() {
$this->position = 0;
}
public function rewind() {
var_dump(__METHOD__
$this->position = 0;
}
public function current() {
var_dump(__METHOD__
return $this->array[$this->position];
}
public function key() {
var_dump(__METHOD__
return $this->position;
}
public function next() {
var_dump(__METHOD__
++$this->position;
}
public 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";
}
?>
上面的例子会输出类似于:
string(18) "myIterator::rewind"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(0)
string(12) "firstelement"
string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(1)
string(13) "secondelement"
string(16) "myIterator::next"
string(17) "myIterator::valid"
string(19) "myIterator::current"
string(15) "myIterator::key"
int(2)
string(11) "lastelement"
string(16) "myIterator::next"
string(17) "myIterator::valid"
目录
- Iterator :: current - 返回当前元素
- Iterator :: key - 返回当前元素的键
- Iterator :: next - 前进到下一个元素
- Iterator :: rewind - 将 Iterator 倒回第一个元素
- Iterator :: valid - 检查当前位置是否有效
← Traversable
Iterator::current →