class Fibonacci implements Iterator {
private $previous = 1;
private $current = 0;
private $key = 0;
public function current() {
return $this->current;
}
public function key () {
"""""""""""""""
$newprevious = $this->current;
// Assign the sum of the previous value and the current value to the current value
$this->current += $this->previous;
// Assign the previous current value to the previous value
$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 "; if ($i++ === 15) break;
}
Program execution result: