Skip to content

Instantly share code, notes, and snippets.

@geekcom
Created May 8, 2018 12:08
Show Gist options
  • Save geekcom/8da80db988e3130cd97129410ad5e17d to your computer and use it in GitHub Desktop.
Save geekcom/8da80db988e3130cd97129410ad5e17d to your computer and use it in GitHub Desktop.
Spl iterator example
<?php
class Alfabeto implements Iterator
{
protected $_current;
protected $_key;
public function rewind()
{
$this->_current = 'a';
$this->_key = 1;
}
public function current()
{
return $this->_current;
}
public function key()
{
return $this->_key;
}
public function next()
{
$this->_current++;
$this->_key++;
return $this->_current;
}
public function valid()
{
return ($this->key() <= 26);
}
}
class Vogais extends FilterIterator
{
public function accept()
{
return in_array($this->current(), ['a', 'e', 'i', 'o', 'u']);
}
}
$alfabeto = new Alfabeto();
$vogais = new Vogais($alfabeto);
//listar alfabeto
echo 'Listando letras do alfabeto ...' . PHP_EOL;
foreach ($alfabeto as $posicao => $letra){
var_dump($posicao . ' => ' . $letra);
}
PHP_EOL;
//listar vogais
echo 'Listando vogais ...' . PHP_EOL;
foreach ($vogais as $posicao => $letra){
var_dump($posicao . ' => ' . $letra);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment