PHP5開始支持了接口, 而且內置了Iterator接口, 因此若是你定義了一個類,並實現了Iterator接口,那麼你的這個類對象就是ZEND_ITER_OBJECT,不然就是ZEND_ITER_PLAIN_OBJECT.php
對於ZEND_ITER_PLAIN_OBJECT的類,foreach會經過HASH_OF獲取該對象的默認屬性數組,而後對該數組進行foreach.數組
而對於ZEND_ITER_OBJECT的類對象,則會經過調用對象實現的Iterator接口相關函數來進行foreach。函數
/** * @author 簡明現代魔法 http://www.nowamagic.net */ class MyIterator implements Iterator { private $var = array(); public function __construct($array) { if (is_array($array)) { $this->var = $array; } } public function rewind() { echo "倒回第一個元素\n"; reset($this->var); } public function current() { $var = current($this->var); echo "當前元素: $var\n"; return $var; } public function key() { $var = key($this->var); echo "當前元素的鍵: $var\n"; return $var; } public function next() { $var = next($this->var); echo "移向下一個元素: $var\n"; return $var; } public function valid() { $var = $this->current() !== false; echo "檢查有效性: {$var}\n"; return $var; } } $values = array(1,2,3); $it = new MyIterator($values); foreach ($it as $k => $v) { print "此時鍵值對 -- key $k: value $v\n\n"; }
通常的迭代器內部須要下面的方法:this
運行一下上述代碼的結果,能夠看一下迭代器的運行原理:spa
倒回第一個元素 當前元素: 1 檢查有效性: 1 當前元素: 1 當前元素的鍵: 0 此時鍵值對 -- key 0: value 1 移向下一個元素: 2 當前元素: 2 檢查有效性: 1 當前元素: 2 當前元素的鍵: 1 此時鍵值對 -- key 1: value 2 移向下一個元素: 3 當前元素: 3 檢查有效性: 1 當前元素: 3 當前元素的鍵: 2 此時鍵值對 -- key 2: value 3 移向下一個元素: 當前元素: 檢查有效性:
固然,你也能夠換種方法實現迭代器裏面五個固定功能方法:.net
<?php //include 'xphp.php'; class Sample implements Iterator{ private $_items; private $_current = 0; public function __construct(&$data){ $this -> _items = $data; } public function current(){ return $this -> _items[$this ->_current]; } public function next(){ $this ->_current ++; } public function key(){ return $this ->_current; } public function rewind(){ $this ->_current = 0; } public function valid(){ return isset($this -> _items[$this -> _current]); } } $arr = array(1, 2, 3); $arr2 = new Sample($arr); foreach($arr2 as $key => $value){ echo $key . '==' . $value . '<br>'; }
用法(實現一個斐波納契數列):code
/** * @author 簡明現代魔法 http://www.nowamagic.net */ class Fibonacci implements Iterator { private $previous = 1; private $current = 0; private $key = 0; public function current() { return $this->current; } public function key() { return $this->key; } public function next() { // 關鍵在這裏 // 將當前值保存到 $newprevious $newprevious = $this->current; // 將上一個值與當前值的和賦給當前值 $this->current += $this->previous; // 前一個當前值賦給上一個值 $this->previous = $newprevious; $this->key++; } public function rewind() { $this->previous = 1; $this->current = 0; $this->key = 0; } public function valid() { return true; } } $seq = new Fibonacci; $i = 0; foreach ($seq as $f) { echo "$f "; if ($i++ === 15) break; }
php SPL(Standard PHP Library)標準庫封裝的一些的迭代器,遍歷文件夾,遍歷文件等等。對象
http://blog.csdn.net/uuleaf/article/details/7635996blog
http://php.net/manual/en/spl.iterators.php接口