<?php
// 使对象可以像数组一样进行foreach循环,要求属性必须是私有。(Iterator模式的PHP实现,写一类实现Iterator接口)
class Test implements Iterator{
private $item = array('id'=>1,'name'=>'php');
public function rewind(){
reset($this->item);
}
public function current(){
return current($this->item);
}
public function key(){
return key($this->item);
}
public function next(){
return next($this->item);
}
public function valid(){
return($this->current()!==false);
}
}
// 测试
$t = new Test;
foreach($t as $k=>$v){
echo $k.'->'.$v.PHP_EOL;
}
本文展示了如何在PHP中实现Iterator接口,使自定义类的对象能够像数组一样被foreach循环遍历。通过定义`rewind`, `current`, `key`, `next`和`valid`方法,实现了对类私有属性的迭代操作。示例中创建了一个名为`Test`的类,并在测试部分展示了如何使用foreach循环遍历此类实例。
121

被折叠的 条评论
为什么被折叠?



