Home > Article > Backend Development > [php predefined interface] iterator
The content shared in this article is the [php predefined interface] iterator. Now I share it with everyone. Friends in need can refer to the content of this article
Iterator (Iterator) Interface
Introduction: An interface that can internally iterate its own external iterator or class.
Explanation of specific functions
Interface summary:
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:
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) interface
Introduction: An interface that can internally iterate its own external iterator or class.
Explanation of specific functions
Interface summary:
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:
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?>
Related recommendations:
PHP predefined variables Detailed explanation
php predefined variable method
The above is the detailed content of [php predefined interface] iterator. For more information, please follow other related articles on the PHP Chinese website!