Created
May 8, 2018 12:08
-
-
Save geekcom/8da80db988e3130cd97129410ad5e17d to your computer and use it in GitHub Desktop.
Spl iterator example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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