<?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";
}
PHP 设计模式之迭代器模式
最新推荐文章于 2022-11-29 15:27:22 发布