迭代都知道,其实就是foreach 对一个数组,对象,进行遍历,<br />提供一种方法顺序访问一个聚合函数对象中各个元素,而又不需暴露该对象的内部表示<br />定义游标指针,操作依次指向下一个,展示当前指针数据,遍历出所有数据<br />通过while 判断,foreach 的工作
interface MsgIterator
{
public function First();
public function Next();
public function IsDone();
public function CurrentItem();
}
// 迭代器
class MsgIteratorAsc implements MsgIterator
{
private $list;
private $index;
public function __construct($list)
{
$this->list = $list;
$this->index = 0;
}
public function First()
{
$this->index = 0;
}
public function Next()
{
$this->index++;
}
public function IsDone()
{
return $this->index >= count($this->list);
}
public function CurrentItem()
{
return $this->list[$this->index];
}
}
interface Message
{
public function CreateIterator($list);
}
class MessageAsc implements Message
{
public function CreateIterator($list)
{
return new MsgIteratorAsc($list);
}
}
// 要发的短信号码列表
$mobileList = [
'13111111111',
'13111111112',
'13111111113',
'13111111114',
'13111111115',
'13111111116',
'13111111117',
'13111111118',
];
// 服务器脚本
$serverA = new MessageAsc();
$iteratorA = $serverA->CreateIterator($mobileList);
while (!$iteratorA->IsDone()) {
echo $iteratorA->CurrentItem(), PHP_EOL;
$iteratorA->Next();
}