Home > php教程 > php手册 > body text

PHP design pattern iterator pattern, php design pattern

WBOY
Release: 2016-07-06 14:24:46
Original
810 people have browsed it

PHP design pattern iterator pattern, PHP design pattern

Traverse the internal elements of an aggregate object without exposing the object without knowing the internal implementation. Internally represented, this is the definition of the PHP iterator pattern.

Applicable scenarios:
Access the contents of an aggregate object without exposing its internal representation
Supports multiple traversals of aggregate objects
Provide a unified interface for traversing different aggregate structures

Iterator pattern example:

<&#63;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";
}
Copy after login

The above is the entire content of this article. I hope it will be helpful for everyone to learn PHP design patterns.

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template