rfc:generators
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
rfc:generators [2012/12/23 23:44] – Add ::throw() method nikic | rfc:generators [2017/09/22 13:28] (current) – external edit 127.0.0.1 | ||
---|---|---|---|
Line 459: | Line 459: | ||
==== Cloning a generator ==== | ==== Cloning a generator ==== | ||
- | Generators | + | Generators |
- | used to create a '' | + | |
- | <code php> | + | Support |
- | class RewindableGenerator implements Iterator { | + | |
- | protected $original; | + | |
- | protected $current; | + | |
- | + | ||
- | public function __construct(Generator $generator) { | + | |
- | $this-> | + | |
- | $this-> | + | |
- | } | + | |
- | + | ||
- | public function rewind() { | + | |
- | if ($this-> | + | |
- | $this-> | + | |
- | $this-> | + | |
- | } | + | |
- | + | ||
- | public function valid() { | + | |
- | if (!$this-> | + | |
- | return $this-> | + | |
- | } | + | |
- | + | ||
- | public function current() { | + | |
- | if (!$this-> | + | |
- | return $this-> | + | |
- | } | + | |
- | + | ||
- | public function key() { | + | |
- | if (!$this-> | + | |
- | return $this-> | + | |
- | } | + | |
- | + | ||
- | public function next() { | + | |
- | if (!$this-> | + | |
- | $this-> | + | |
- | } | + | |
- | + | ||
- | public function send($value) { | + | |
- | if (!$this-> | + | |
- | return $this-> | + | |
- | } | + | |
- | + | ||
- | public function close() { | + | |
- | $this-> | + | |
- | if ($this-> | + | |
- | $this-> | + | |
- | } | + | |
- | } | + | |
- | } | + | |
- | + | ||
- | function rewindable(Generator $generator) { | + | |
- | return new RewindableGenerator($generator); | + | |
- | } | + | |
- | </ | + | |
- | + | ||
- | It can be then used as follows: | + | |
- | + | ||
- | <code php> | + | |
- | function xrange($start, | + | |
- | | + | |
- | yield $i; | + | |
- | } | + | |
- | } | + | |
- | + | ||
- | $range = rewindable(xrange(0, 5)); | + | |
- | foreach ($range as $i) { | + | |
- | echo $i, " | + | |
- | } | + | |
- | foreach ($range as $i) { | + | |
- | echo $i, " | + | |
- | } | + | |
- | </ | + | |
- | + | ||
- | This will correctly output the 0..5 range twice. | + | |
==== Closing a generator ==== | ==== Closing a generator ==== |
rfc/generators.1356306285.txt.gz · Last modified: 2017/09/22 13:28 (external edit)