在 PHP 中,迭代器模式通常涉及两个主要角色:迭代器(Iterator)和可迭代对象(Iterable)。以下是一个简单的 PHP 迭代器模式的示例:
<?php
// 迭代器接口
interface IteratorInterface {
public function hasNext();
public function next();
}
// 可迭代对象接口
interface IterableInterface {
public function getIterator(): IteratorInterface;
}
// 具体迭代器类
class MyIterator implements IteratorInterface {
private $index = 0;
private $data;
public function __construct(array $data) {
$this->data = $data;
}
public function hasNext() {
return $this->index < count($this->data);
}
public function next() {
if ($this->hasNext()) {
$item = $this->data[$this->index];
$this->index++;
return $item;
} else {
return null;
}
}
}
// 具体可迭代对象类
class MyIterable implements IterableInterface {
private $data;
public function __construct(array $data) {
$this->data = $data;
}
public function getIterator(): IteratorInterface {
return new MyIterator($this->data);
}
}
// 客户端代码
$data = [1, 2, 3, 4, 5];
$iterable = new MyIterable($data);
$iterator = $iterable->getIterator();
while ($iterator->hasNext()) {
echo $iterator->next() . "\n";
}
在这个例子中,IteratorInterface 定义了迭代器的基本方法,包括 hasNext 和 next。IterableInterface 定义了获取迭代器的方法。
MyIterator 类是具体的迭代器类,实现了 IteratorInterface 接口,负责遍历一个数组。MyIterable 类是具体的可迭代对象类,实现了 IterableInterface 接口,负责返回一个迭代器。
客户端代码创建了一个可迭代对象,并使用迭代器遍历其元素。
迭代器模式可以使代码更加模块化,允许客户端代码在不了解聚合对象内部结构的情况下遍历元素。在 PHP 中,迭代器模式已经被集成到 SPL(Standard PHP Library)中,因此可以直接使用 SPL 提供的迭代器相关类。
转载请注明出处:http://www.zyzy.cn/article/detail/11955/PHP