欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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();}