迭代器模式
- 不理解外部实现前提下,遍历一个对象
// 继承内置的<a href="https://www.gaodaima.com/tag/%e8%bf%ad%e4%bb%a3" title="查看更多关于迭代的文章" target="_blank">迭代</a>器接口,实现五个办法
class Alluser implements \Iterator{
private $ids; // 存入所有须要迭代的数据
private $index; // 记录以后迭代器地位
public function __construct(){
$rlt = "select id from user";
$this->ids = $rlt-。fetch();
}
public function current() {
return $this->ids[$this->index];
}
// 下一个元素
public function next(){
$this->index++;
}
// 验证元素是否存在
public function valid(){
return !empty($this->ids[$this->index]);
}
// 初始化迭代器到头部
public function rewind(){
$this->index = 0;
}
// 获取以后索引
public function key(){
return $this->index;
}
}
$users = new AllUser();
foreach($users as $user){
var_dump($user);
}