Traversing the internal elements of an aggregate object without exposing the internal representation of the object without knowing the internal implementation is the definition of the PHP iterator pattern.
Applicable scenarios:
Access the contents of an aggregate object without exposing its internal representation
Support multiple traversals of aggregate objects
Provide a unified interface for traversing different aggregate structures
Iterator pattern instance:
<?php class ConcreteIterator implements Iterator{ private $position = 0; private $arr; function __construct(array $arr){ $this->arr = $arr; } function rewind(){ $this->position = 0; } function current(){ return $this->arr[$this->position]; } function key(){ return $this->position; } function next(){ ++$this->position; } function valid(){ return isset($this->arr[$this->position]); } } $arr = array('xiao hong','xiao ming','xiaohua'); $concreteIterator = new ConcreteIterator($arr); foreach ($concreteIterator as $key => $value) { echo $key."=>".$value."\n"; }
The above is the entire content of this article. I hope it will be helpful to everyone in learning PHP design patterns.
The above introduces the PHP factory pattern and the iterator pattern of the PHP design pattern, including the content of the PHP factory pattern. I hope it will be helpful to friends who are interested in PHP tutorials.