关于php:php设计模式九-迭代器模式

迭代器模式

  1. 不理解外部实现前提下,遍历一个对象
// 继承内置的迭代器接口,实现五个办法
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);
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理