PHP 5 provides a way for objects to be defined so it is possible to iterate through a list of items, with, for example a foreach statement. By default, all visible properties will be used for the iteration. PHP5提供了一种迭代(iteration)对象的功能,就像使用数组那样,可以通过foreach 来遍历对象中的属性。默认情况下,在外部迭代只能得到外部可见的属性的值。
Example #1 简单的对象迭代
<?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) {
print "$key => $value
";
}
echo "
";
$class->iterateVisible();
?>
以上例程会输出:
var1 => value 1 var2 => value 2 var3 => value 3 MyClass::iterateVisible: var1 => value 1 var2 => value 2 var3 => value 3 protected => protected var private => private var
如上所示, the foreach 遍历了所有 可见的 属性. 你也可以通过实现PHP 5自带的 Iterator接口来实现迭代. 使用Iterator接口可以让对象自行决定如何迭代自已。
Example #2 实现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
";
reset($this->var);
}
public function current() {
$var = current($this->var);
echo "current: $var
";
return $var;
}
public function key() {
$var = key($this->var);
echo "key: $var
";
return $var;
}
public function next() {
$var = next($this->var);
echo "next: $var
";
return $var;
}
public function valid() {
$var = $this->current() !== false;
echo "valid: {$var}
";
return $var;
}
}
$values = array(1,2,3);
$it = new MyIterator($values);
foreach ($it as $a => $b) {
print "$a: $b
";
}
?>
以上例程会输出:
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:
你也可以让类实现IteratorAggregate接口,这样你的类就不用强制性地实现 Iterator接口中的所有方法。
Example #3 通过IteratorAggregate来实现对象迭代
<?php
class MyCollection implements IteratorAggregate
{
private $items = array();
private $count = 0;
// Required definition of interface IteratorAggregate
public function getIterator() {
return new MyIterator($this->items);
}
public function add($value) {
$this->items[$this->count++] = $value;
}
}
$coll = new MyCollection();
$coll->add('value 1');
$coll->add('value 2');
$coll->add('value 3');
foreach ($coll as $key => $val) {
echo "key/value: [$key -> $val]
";
}
?>
以上例程会输出:
rewinding current: value 1 valid: 1 current: value 1 key: 0 key/value: [0 -> value 1] next: value 2 current: value 2 valid: 1 current: value 2 key: 1 key/value: [1 -> value 2] next: value 3 current: value 3 valid: 1 current: value 3 key: 2 key/value: [2 -> value 3] next: current: valid:
Note:
请查看SPL Extension了解更多Iterator相关信息。