php中的设计模式之迭代器模式
程序员文章站
2022-05-31 08:43:08
...
myiterator = $iterator; $this->position = 0 ; } // 获取当前 function current() { return $this->myiterator[$this->position]; } // 下个index function next(){ ++$this->position ; } //获得key(下标) function key(){ return $this->position; } function value(){ return $this->myiterator[$this->position]; } // 重新遍历 function rewind() { $this->position = 0; } function valid(){ return isset($this->myiterator[$this->position]); } }// 应用 /*$aData = array('a','b','c');$myiterator = new myiterator($aData); while($myiterator->valid()){ $myiterator->next();}*/// (2)搭建自己的容器 interface container { public function getIterator();}class myContainer implements container{ private $iterator ; public function __construct($data){ $this->iterator = new myiterator($data) ; } public function getIterator(){ return $this->iterator; } }// 应用实例$data = array('a','b','c');$myContainer = new myContainer($data) ;// 获得迭代器$myiterator = $myContainer->getIterator();while($myiterator->valid()){ var_dump($myiterator->current()); $myiterator->next();}