note 91068 modified in class.iterator by danbrown

From: Date: Mon, 25 May 2009 22:17:27 +0000
Subject: note 91068 modified in class.iterator by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155998@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; } ?> --was-- 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; } http://php.net/manual/en/class.iterator.php

« previous php.notes (#155998) next »