本篇文章分享的内容是【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中文网其他相关文章!