note 93580 added to class.iterator
| From: | AnthonySterling at osu1 dot php dot net | Date: | Thu, 17 Sep 2009 09:20:03 +0000 |
| Subject: | note 93580 added to class.iterator | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-160770@lists.php.net to get a copy of this message | ||
Here's a Fibonacci example using the formula, rather than addition.
<?php
/**
* @author Anthony Sterling
*/
class FibonacciSequence implements Iterator
{
protected
$limit = 0;
protected
$key = 0;
public function __construct($limit = 0)
{
$this->limit = (integer)$limit;
}
public function current()
{
return round(
(pow(((1 + sqrt(5)) / 2), $this->key) - pow((-1 / (1 + sqrt(5)) / 2), $this->key)) /
sqrt(5),
null
);
}
public function key()
{
return $this->key;
}
public function next()
{
$this->key++;
}
public function rewind()
{
$this->key = 0;
}
public function valid()
{
return $this->key < $this->limit;
}
}
foreach(new FibonacciSequence() as $number)
{
printf(
'%d<br />',
$number
);
}
/*
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
*/
?>
Anthony.
----
Server IP: 64.71.164.2
Probable Submitter: 212.159.198.13
----
Manual Page -- http://www.php.net/manual/en/class.iterator.php
Edit -- https://master.php.net/note/edit/93580
Del: integrated -- https://master.php.net/note/delete/93580/integrated
Del: useless -- https://master.php.net/note/delete/93580/useless
Del: bad code -- https://master.php.net/note/delete/93580/bad+code
Del: spam -- https://master.php.net/note/delete/93580/spam
Del: non-english -- https://master.php.net/note/delete/93580/non-english
Del: in docs -- https://master.php.net/note/delete/93580/in+docs
Del: other reasons-- https://master.php.net/note/delete/93580
Reject -- https://master.php.net/note/reject/93580
Search -- https://master.php.net/manage/user-notes.php