Php/docs/class.iterator
(No version information available, might only be in Git)
简介
可在内部迭代自己的外部迭代器或类的接口。
接口摘要
范例
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";}?>
以上例程的输出类似于:
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"
Table of Contents
- Iterator::current — 返回当前元素
- Iterator::key — 返回当前元素的键
- Iterator::next — 向前移动到下一个元素
- Iterator::rewind — 返回到迭代器的第一个元素
- Iterator::valid — 检查当前位置是否有效
/* 方法 */