從手冊中查到的解釋是:php
Iterator extends 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 ) }
當一個實現了Iterator
接口的對象,被foreach
遍歷時,會自動調用這些方法。調用的循序是:rewind()
-> valid()
-> current()
-> key()
-> next()
this
下面來看一下簡單的代碼:scala
class 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"; }
以上會輸出:code
/Users/thanatos/Web/study/blean.php:15:string 'myIterator::rewind' (length=18) /Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17) /Users/thanatos/Web/study/blean.php:20:string 'myIterator::current' (length=19) /Users/thanatos/Web/study/blean.php:25:string 'myIterator::key' (length=15) /Users/thanatos/Web/study/blean.php:43:int 0 /Users/thanatos/Web/study/blean.php:43:string 'firstelement' (length=12) --------------------------- /Users/thanatos/Web/study/blean.php:30:string 'myIterator::next' (length=16) /Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17) /Users/thanatos/Web/study/blean.php:20:string 'myIterator::current' (length=19) /Users/thanatos/Web/study/blean.php:25:string 'myIterator::key' (length=15) /Users/thanatos/Web/study/blean.php:43:int 1 /Users/thanatos/Web/study/blean.php:43:string 'secondelement' (length=13) --------------------------- /Users/thanatos/Web/study/blean.php:30:string 'myIterator::next' (length=16) /Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17) /Users/thanatos/Web/study/blean.php:20:string 'myIterator::current' (length=19) /Users/thanatos/Web/study/blean.php:25:string 'myIterator::key' (length=15) /Users/thanatos/Web/study/blean.php:43:int 2 /Users/thanatos/Web/study/blean.php:43:string 'lastelement' (length=11) --------------------------- /Users/thanatos/Web/study/blean.php:30:string 'myIterator::next' (length=16) /Users/thanatos/Web/study/blean.php:35:string 'myIterator::valid' (length=17)