Home  >  Article  >  Backend Development  >  PHP Design Pattern Series - Iterator_PHP Tutorial

PHP Design Pattern Series - Iterator_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 17:52:111049browse

PHP iterator:
Helps in the construction of specific objects that provide a single standard interface for looping or iterating over any type of countable data. (Not particularly commonly used, in PHP)
Usage scenario:
1. Access the contents of an aggregate object without exposing its internal representation.
2. Support multiple traversals of aggregate objects.
3. Provide a unified interface for traversing different aggregate structures (i.e., polymorphic iteration).

PHP code implementation:
[php]
//Iterator: helps construct specific objects that provide a single standard interface for looping or iterating any type of countable data
class MyIterator implements Iterator {
       
Private $var = array();
       
Public function __construct($array) {
$this->var = $array;
}  
       
Public function rewind() {
           reset($this->var); 
}  
       
Public function current() {
$var = current($this->var);
              return $var;                           }  
         
Public function valid() {
$var = $this->current() !== false;
         return $var;
}  
       
Public function next() {
$var = next($this->var);
          return $var;
}  
       
Public function key() {
          $var = key($this->var);
              return $var;                           }  
}
$values ​​= array('a', 'b', 'c');
$it = new MyIterator($values);
foreach ($it as $a => $b) {
Print "$a: $b
";
}
?>

Author: initphp


http://www.bkjia.com/PHPjc/478134.html

truehttp: //www.bkjia.com/PHPjc/478134.htmlTechArticlePHP Iterator: Helps in constructing specific objects that provide a single standard interface for looping or iterating any type Countable data. (Not particularly common, in PHP) Use...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn