Iterator mode (Iterator), also called cursor mode. Provides a way to access individual elements in a container (Container) object without exposing the object's internal details.
You should consider using the iterator pattern when you need to access an aggregation object, and regardless of what these objects need to traverse. In addition, you may want to consider using the iterator pattern when there are multiple ways to traverse the aggregation. The iterator pattern provides a unified interface for traversing different aggregation structures, such as start, next, end, or current.
The iterator interface Iterator is provided in the PHP standard library (SPL) to implement the iterator pattern and implement the interface.
<?phpclass Sample implements Iterator {private $_items; Public function __construct (& $data) {$this->_items = $data; Public function current () {return to current ($this->_items); Public function Next () {Next ($this->_items); } Public Function key () {return key ($this->_items); } Public Function Rewind () {Reset ($this->_items); } public Function valid () {return ($this->current ()!== FALSE); }}//client$data = Array (1, 2, 3, 4, 5), $sa = new sample ($data), foreach ($sa as $key = = $row) {echo $key, ', $row , ' <br/> ';} /* Output: 0 5 *///yii FrameWork Democlass Cmapiterator implements Iterator {/*** @var array the data to be iterate D through*/Private $_d;/*** @var array list of keys in the map*/private $_keys;/*** @var mixed current key*/PR Ivate $_key;/*** constructor.* @param array The data to is iterated through*/public function __construct (& $data) {$this->_d=& $data; $this->_keys=array_keys ($data); }/*** rewinds Internal Array pointer.* This method was required by the interface iterator.*/public Function rewind () { $this->_key=reset ($this->_ke YS); }/*** Returns the "The current" array element.* This method are required by the interface iterator.* @return mixed the Key of the current array element*/public Function key () {return $this->_key; }/*** Returns The current array element.* This method was required by the interface iterator.* @return mixed the current AR Ray element*/Public Function current () {return $this->_d[$this->_key]; }/*** Moves The internal pointer to the next array element.* This method was required by the interface iterator.*/Publi C function Next () { $this->_key=next ($this->_keys); }/*** Returns Whether there is a element at current position.* This method was required by the interface iterator.* @retur n boolean*/Public Function valid () {return $this->_key!==false; }} $data = Array (' s1 ' + =, ' s2 ' = ' = ', ' S3 '); $it = new Cmapiterator ($data); foreach ($it as $row) {echo $row, ' <br/> ';} /* Output: 112233 */?>
PHP design mode-iterator mode