PHP5提供迭代器就像一個未實例化的對象容器,一個對象的數組集合。默認地,所有可見的屬性將用來迭代(反復)。
PHP代碼如下:
class MyClass {
public $var1 = 'value 1';
public $var2 = 'value 2';
public $var3 = 'value 3';
protected $protected = 'protected var';
private $private = 'private var';
function iterateVisible() {
echo "MyClass::iterateVisible:";
foreach ( $this as $key => $value ) {
print "$key => $value"." ";
}
}
}
$class = new MyClass ( );
foreach ( $class as $key => $value ) {
$arr = array();
$arr[$key] = $value."00";
print_r($arr);
}
$class->iterateVisible();
如輸出顯示,foreach重述能通過全部可見變量訪問,並可以引用操作(其中並不改變裡面的數據結構)。更進一步,你可以實現一個PHP5的指定的內在接口迭代器(Iterator)。允許對象描述什麼是對象重述和對象如何被重述的。
PHP代碼如下:
class MyIterator implements Iterator{
private $var = array();
public function __construct($array) {
if (is_array($array)){
$this->var = $array;
}
}
public function rewind() {
echo "rewinding\n";
reset($this->var);
}
public function current() {
$var = current($this->var);
echo "current: $var\n";
return $var;
}
public function key() {
$var = key($this->var);
echo "key: $var\n";
return $var;
}
public function next() {
$var = next($this->var);
echo "next: $var\n";
return $var;
}
public function valid() {
$var = $this->current() !== false;
echo "valid: {$var}\n";
return $var;
}
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a => $b<br>\n";
}
上例將輸出:
rewinding current:1 valid : 1 current:1 key : 0 0 => 1
next : 2 current:2 valid : 1 current:2 key : 1 1 => 2
next : 3 current:3 valid : 1 current:3 key : 2 2 => 3
next : current: valid :
valid:1表示為真,即為true。需要說明的是用Iterator接口包含rewind()、current()、key()、next()、valid()五個函數(實際上是Iterator::rewind Iterator::current...順序可以打亂),須全部用上不然會出錯。
你也可以讓類實現IteratorAggregate接口,這樣你的類就不用強制性地實現 Iterator接口中的所有方法。
PHP代碼如下:
<?php
class MyCollection implements IteratorAggregate{
private $items = array();
private $count =0;
public function getIterator() {
return new MyIterator($this->items);
}
public function add($value){
$this->items[$this->count++] = $value;
}
}
$coll = new MyCollection();
$coll->add('new1');
$coll->add('new2');
$coll->add('new3');
foreach($coll as $k=>$v){
echo "[".$k."->".$v."]"."<br/>";
}?>
上例將輸出:
rewinding current: new1 valid: 1 current: new1 key: 0 [0->new1]
next: new2 current: new2 valid: 1 current: new2 key: 1 [1->new2]
next: new3 current: new3 valid: 1 current: new3 key: 2 [2->new3]
next: current: valid:
這個迭代實際上是IteratorAggregate::getIterator,即須用上getIterator()函數,作用是獲取一個外部迭代器(Iterator 或 Traversable ),實現了 Iterator 或 Traversable 接口的類的一個實例。
一個簡明易懂例子:
class sample implements Iterator {
private $_items = array(1,2,3,4,5,6,7);
public function __construct() {
;//void
}
public function rewind() {
reset($this->_items);
}
public function current() {
return current($this->_items);
}
public function key() {
return key($this->_items);
}
public function next() {
return next($this->_items);
}
public function valid() {
return ( $this->current() !== false );
}
}
$sa = new sample();
foreach($sa as $key => $val){
print $key . "=>" .$val;
}