2.15. 迭代器模式

未匹配的标注

作用

我感觉就是统一了,其他没什么感觉。

实现Iterator就是迭代器了


<?php

class Chapter
{
    public $content;
    public $title;

    public function __construct($title,$content)
    {
        $this->title = $title;
        $this->content = $content;
    }
}

Class ChapterList implements \Countable,\Iterator
{
    protected $chapters = []; //所有章节
    protected $index = 0; //当前看到的章节索引
    public function addChapter(Chapter $chapter)
    {
        $this->chapters[] = $chapter;
    }

    public function count()  //总章节数
    {
        return count( $this->chapters);
    }

    public function rewind() { $this->index = 0; } //重置索引
    public function current(){ return $this->chapters[$this->index]; } //当前数据
    public function next() { return $this->index++; } //下一章
    public function valid(){ return isset($this->chapters[$this->index]); } //是否存在当前索引
    public function key(){ return $this->index; } //当前所在索引
}


//运行
$chapterList = new ChapterList();
for($i =0;$i < 10;$i++)
$chapterList->addChapter(
    new Chapter("第{$i}章\n","{$i}章的内容\n")
);


echo '总章节:'.$chapterList->count().PHP_EOL;

echo  '当前章节标题'.$chapterList->current()->title;
$chapterList->next();
echo  '下一章节标题'.$chapterList->current()->title;



本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~