Home >Backend Development >PHP Tutorial >PHP Design Pattern Series - Iterator_PHP Tutorial
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