Created
September 17, 2017 04:18
-
-
Save tkouleris/548915cb8caf361d74d7930c9c5b135e to your computer and use it in GitHub Desktop.
Iterator Design Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class IntegerRange implements Iterator{ | |
| private $start; | |
| private $end; | |
| private $current; | |
| public function __construct($start, $end){ | |
| $this->start = $start; | |
| $this->end = $end; | |
| $this->current = $start; | |
| } | |
| public function rewind(){ | |
| $this->current = $this->start; | |
| } | |
| public function current(){ | |
| return $this->current; | |
| } | |
| public function key(){ | |
| return $this->current; | |
| } | |
| public function next() | |
| { | |
| ++$this->current; | |
| if($this->valid()){ | |
| return false; | |
| } | |
| return $this->current; | |
| } | |
| public function valid() | |
| { | |
| if($this->current > $this->end){ | |
| return false; | |
| } | |
| return true; | |
| } | |
| } | |
| $range = new IntegerRange(1, 10); | |
| foreach($range as $value){ | |
| echo "$value "; | |
| } | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment