PHP 设计模式之迭代器模式

来源:互联网 发布:内部网络故障诊断工具 编辑:程序博客网 时间:2024/06/07 17:45
<?php// 在不需要了解内部实现的前提条件下,可以遍历一个聚合对象的内部元素// 相比于传统的编程模式,迭代器模式可以隐藏遍历元素所需的操作class AllUser implements Iterator{    private $ids;    private $index;    public function __construct()    {        $this->ids = [1, 2, 3, 4, 5, 6, 7];    }    public function current()    {        return $this->ids[$this->index];    }    public function next()    {        $this->index++;    }    // 第一个调用 valid    public function valid()    {        return $this->index < count($this->ids);    }    // 重置整个迭代器    public function rewind()    {        $this->index = 0;    }    // 表示在迭代器中的位置    public function key()    {        return $this->index;    }}$users = new AllUser;foreach ($users as $user) {    print_r($user);    echo "\n";}
原创粉丝点击