PHP对象迭代
介绍
从PHP5开始,可以遍历对象的所有可见项的列表。可以使用foreach循环以及迭代器接口来执行迭代。PHP中还有IteratorAggregate接口,可用于此目的
使用foreach循环
示例
<?php class myclass{ private $var; protected $var1; public $x, $y, $z; public function __construct(){ $this->var="private variable"; $this->var1=TRUE; $this->x=100; $this->y=200; $this->z=300; } public function iterate(){ foreach ($this as $key => $value) { print "$key => $value\n"; } } } $obj = new myclass(); foreach($obj as $key => $value) { print "$key => $value\n"; } echo "\n"; $obj->iterate(); ?>
输出结果
输出如下-
x => 100 y => 200 z => 300 var => private variable var1 => 1 x => 100 y => 200 z => 300
使用迭代器接口
此接口定义以下抽象方法,在以下示例中将实现
abstract public current ( void ) : mixed abstract public key ( void ) : scalar abstract public next ( void ) : void abstract public rewind ( void ) : void abstract public valid ( void ) : bool
Iterator::current—返回当前元素
Iterator::key—返回当前元素的键
Iterator::next-移至下一个元素
Iterator::rewind—将Iterator倒退到第一个元素
Iterator::valid—检查当前位置是否有效
以下示例通过实现Iterator接口演示了对象迭代
示例
<?php class myclass implements Iterator{ private $arr = array('a','b','c'); public function rewind(){ echo "rewinding\n"; reset($this->arr); } public function current(){ $var = current($this->arr); echo "current: $var\n"; return $var; } public function key() { $var = key($this->arr); echo "key: $var\n"; return $var; } public function next() { $var = next($this->arr); echo "next: $var\n"; return $var; } public function valid(){ $key = key($this->arr); $var = ($key !== NULL && $key !== FALSE); echo "valid: $var\n"; return $var; } } $obj = new myclass(); foreach ($obj as $k => $v) { print "$k: $v\n"; } ?>
输出结果
上面的代码产生以下结果-
rewinding valid: 1 current: a key: 0 0: a next: b valid: 1 current: b key: 1 1: b next: c valid: 1 current: c key: 2 2: c next: valid: