這篇文章分享的內容是【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中文網其他相關文章!