您的位置:首页技术文章
文章详情页

PHP基础之类和对象14——遍历对象

【字号: 日期:2022-09-14 18:39:26浏览:2作者:猪猪

PHP 5 提供了一种定义对象的方法使其可以通过单元列表来遍历,例如用 foreach 语句。默认情况下,所有可见属性都将被用于遍历。

Example #1 简单的对象遍历

class MyClass{ public $var1 = 1; public $var2 = 2; public $var3 = 3; protected $protected = ’protected var’; private $private = ’private var’; function iterateVisible(){echo 'MyClass::iterateVisible:<br>';foreach($this as $key => $value){ print '$key=>$value<br>';} }} $class = new MyClass();foreach($class as $key => $value){ print '$key => $value<br>';}echo '<br>';$class->iterateVisible();

输出结果:

var1 => 1

var2 => 2

var3 => 3

MyClass::iterateVisible:

var1=>1

var2=>2

var3=>3

protected=>protected var

private=>private var

如上所示,foreach 遍历了所有其能够访问的可见属性。

更进一步,可以实现 Iterator接口。可以让对象自行决定如何遍历以及每次遍历时那些值可用。

class MyIterator implements Iterator{ private $var = array(); public function __construct($array) {if(is_array($array)){ $this->var = $array;} } public function rewind(){echo 'rewinding<br>';reset($this->var); } public function current(){$var = current($this->var);echo 'current:$var<br>';return $var; } public function key(){$var = key($this->var);echo 'key:$var<br>';return $var; } public function next(){$var = next($this->var);echo 'next:$var<br>';return $var; } public function valid(){$var = $this->current()!==false;echo 'valid:$var<br>';return $var; }}$values = array(1,2,3);$it = new MyIterator($values);foreach($it as $a => $b){ print '$a:$b<br>';}

输出结果:

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 方法。IteratorAggregate 只需要实现一个方法 IteratorAggregate::getIterator(),其应返回一个实现了 Iterator 的类的实例。

Example #3 通过实现 IteratorAggregate 来遍历对象

include_once(’class2.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(’1’);$coll -> add(’2’);$coll -> add(’3’);foreach($coll as $k => $v){ echo 'key/value:[$k->$v]<br><br>';}

输出结果:

rewinding

current:1

valid:1

current:1

key:0

key/value:[0->1]

next:2

current:2

valid:1

current:2

key:1

key/value:[1->2]

next:3

current:3

valid:1

current:3

key:2

key/value:[2->3]

next:

current:

valid:

标签: PHP
相关文章: