Skip to content

Instantly share code, notes, and snippets.

@bdelespierre
Last active December 30, 2015 04:19
Show Gist options
  • Select an option

  • Save bdelespierre/7775130 to your computer and use it in GitHub Desktop.

Select an option

Save bdelespierre/7775130 to your computer and use it in GitHub Desktop.
Fibonnaci numbers generator
<?php
// quick'n dirty
class Fibonacci implements Iterator {
public function __construct () {
$this->rewind();
}
public function __invoke () {
$n = $this->current();
$this->next();
return $n;
}
public function current () {
return $this->n;
}
public function key () {
return $this->k;
}
public function next () {
$this->k++;
if ($this->k == 0)
$this->n = 0;
elseif ($this->k == 1)
$this->n = 1;
else {
$this->n = $this->prev[0] + $this->prev[1];
$this->prev[0] = $this->prev[1];
$this->prev[1] = $this->n;
}
}
public function rewind () {
$this->n = 0;
$this->k = 0;
$this->prev = [0,1];
}
public function valid () {
return true;
}
}
$fibonacci_generator = new Fibonacci;
foreach (range(1,10) as $i)
echo $fibonacci_generator() . "\n";
foreach (range(1,10) as $i)
echo $fibonacci_generator() . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment