PHP设计模式-迭代器 发表于 2017-04-26 | 分类于 PHP | 评论数: | 阅读次数: 本文字数: 3.1k | 阅读时长 ≈ 3 分钟 适用性 遍历对象内部的属性,无需对外暴露内部的构成 下面我们来实现一个迭代器访问学校所有的老师 代码示例 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196namespace iterator;/** * 学校接口 */interface School{ /** * 获取迭代器 * * @return mixed */ public function getIterator();}/** * 迭代器接口 */interface Iterator{ /** * 是否还有下一个 * * @return boolean */ public function hasNext(); /** * 下一个 * * @return object */ public function next(); /** * 当前 * * @return mixed */ public function current(); /** * 当前索引 * * @return mixed */ public function index();}/** * 实验小学实体 */class SchoolExperimental implements School{ /** * 老师集合 * @var */ private $_teachers = []; /** * 魔法方法 * * @param string $name 属性名称 * @return mixed */ public function __get($name='') { $name = '_' . $name; return $this->$name; } /** * 添加老师 * @param string $name */ public function addTeacher($name='') { $this->_teachers[] = $name; } /** * 获取教师迭代器 * * @return mixed */ public function getIterator() { return new TeacherIterator($this); }}/** * 老师迭代实体 */class TeacherIterator implements Iterator{ /** * 索引值 * @var integer */ private $_index = 0; /** * 要迭代的对象 * @var object */ private $_teachers; /** * 构造函数 * * @param School $school */ public function __construct(School $school) { $this->_teachers = $school->teachers; } /** * 是否还有下一个 * * @return boolean */ public function hasNext() { if ($this->_index < count($this->_teachers)) { return true; } return false; } /** * 下一个 * * @return object */ public function next() { if (!$this->hasNext()) { echo NULL; return; } $index = $this->_index + 1; echo $this->_teachers[$index]; } /** * 当前 * * @return mixed */ public function current() { if (!isset($this->_teachers[$this->_index])) { echo NULL; return; } $current = $this->_teachers[$this->_index]; $this->_index += 1; echo $current . "\n"; } /** * 当前索引 * * @return integer */ public function index() { echo $this->_index; }}try { // 初始化一个实验小学 $experimental = new SchoolExperimental(); // 添加老师 $experimental->addTeacher('Griffin'); $experimental->addTeacher('Curry'); $experimental->addTeacher('Mc'); $experimental->addTeacher('Kobe'); $experimental->addTeacher('Rose'); $experimental->addTeacher('Kd'); // 获取教师迭代器 $iterator = $experimental->getIterator(); // 打印所有老师 do { $iterator->current(); } while ($iterator->hasNext());} catch (\Exception $e) { echo 'error:' . $e->getMessage();}