note 91068 added to class.iterator
| From: | GeoffreySneddon at osu1 dot php dot net | Date: | Sat, 23 May 2009 17:42:06 +0000 |
| Subject: | note 91068 added to class.iterator | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-155908@lists.php.net to get a copy of this message | ||
So, playing around with iterators in PHP (coming from languages where I'm spoiled with
generators to do things like this), I wrote a quick piece of code to give the Fibonacci sequence (to
infinity, though only the first terms up to F_{10} are output).
<?php
class Fibonacci implements Iterator {
private $previous = 1;
private $current = 0;
private $key = 0;
public function current() {
return $this->current;
}
public function key() {
return $this->key;
}
public function next() {
$newprevious = $this->current;
$this->current += $this->previous;
$this->previous = $newprevious;
$this->key++;
}
public function rewind() {
$this->previous = 1;
$this->current = 0;
$this->key = 0;
}
public function valid() {
return true;
}
}
$seq = new Fibonacci;
$i = 0;
foreach ($seq as $f) {
echo "$f\n";
if ($i++ === 10) break;
}
----
Server IP: 92.48.74.199
Probable Submitter: 86.165.92.13
----
Manual Page -- http://www.php.net/manual/en/class.iterator.php
Edit -- https://master.php.net/note/edit/91068
Del: integrated -- https://master.php.net/note/delete/91068/integrated
Del: useless -- https://master.php.net/note/delete/91068/useless
Del: bad code -- https://master.php.net/note/delete/91068/bad+code
Del: spam -- https://master.php.net/note/delete/91068/spam
Del: non-english -- https://master.php.net/note/delete/91068/non-english
Del: in docs -- https://master.php.net/note/delete/91068/in+docs
Del: other reasons-- https://master.php.net/note/delete/91068
Reject -- https://master.php.net/note/reject/91068
Search -- https://master.php.net/manage/user-notes.php