Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / PHP

Iterator

Define un cursor con rewind, valid, current, key y next. foreach empieza con rewind, comprueba valid antes de leer y avanza tras el elemento. valid debe comprobar la posición independientemente del valor para que un null o false almacenado no termine el recorrido.

Versión: PHP 8.4; repository runtime, production runtime not attested

Sintaxis

class Steps implements Iterator

Define un cursor con rewind, valid, current, key y next. foreach empieza con rewind, comprueba valid antes de leer y avanza tras el elemento. valid debe comprobar la posición independientemente del valor para que un null o false almacenado no termine el recorrido. El método Iterator::current devuelve el valor de la posición actual y Iterator::key su clave. Aquí Iterator::rewind vuelve a cero, Iterator::valid comprueba si existe el índice y Iterator::next avanza una posición.

class Steps implements Iterator { private int $i=0; private array $v=[null,false,3]; public function rewind():void{$this->i=0;} public function valid():bool{return array_key_exists($this->i,$this->v);} public function current():mixed{return $this->v[$this->i];} public function key():int{return $this->i;} public function next():void{++$this->i;} }
echo json_encode(iterator_to_array(new Steps()));
[null,false,3]

Ejemplos

<?php
class Steps implements Iterator { private int $i=0; private array $v=[null,false,3]; public function rewind():void{$this->i=0;} public function valid():bool{return array_key_exists($this->i,$this->v);} public function current():mixed{return $this->v[$this->i];} public function key():int{return $this->i;} public function next():void{++$this->i;} }
echo json_encode(iterator_to_array(new Steps()));

Resultado

[null,false,3]

Fuentes