Skip to content

Instantly share code, notes, and snippets.

@gorkamu
Created November 9, 2016 09:52
Show Gist options
  • Save gorkamu/40c297d225121156ee65b9c4afc7a843 to your computer and use it in GitHub Desktop.
Save gorkamu/40c297d225121156ee65b9c4afc7a843 to your computer and use it in GitHub Desktop.
Ejemplo de implementación de la interfaz Iterator
<?php
class MiIterador implements Iterator
{
private $var = array();
public function __construct($array)
{
if (is_array($array)) {
$this->var = $array;
}
}
public function rewind()
{
echo "rebobinando\n";
reset($this->var);
}
public function current()
{
$var = current($this->var);
echo "actual: $var\n";
return $var;
}
public function key()
{
$var = key($this->var);
echo "clave: $var\n";
return $var;
}
public function next()
{
$var = next($this->var);
echo "siguiente: $var\n";
return $var;
}
public function valid()
{
$clave = key($this->var);
$var = ($clave !== NULL && $clave !== FALSE);
echo "válido: $var\n";
return $var;
}
}
$valores = array(1,2,3);
$it = new MiIterador($valores);
foreach ($it as $a => $b) {
print "$a: $b\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment