CKTIS / PHP
Iterator
Define um cursor com rewind, valid, current, key e next. foreach começa por rewind, testa valid antes de ler e avança após cada elemento. valid deve seguir a posição independentemente do valor para que um null ou false guardado não termine o percurso.
Versão: PHP 8.4; repository runtime, production runtime not attested
Sintaxe
class Steps implements IteratorDefine um cursor com rewind, valid, current, key e next. foreach começa por rewind, testa valid antes de ler e avança após cada elemento. valid deve seguir a posição independentemente do valor para que um null ou false guardado não termine o percurso. O método Iterator::current devolve o valor da posição atual e Iterator::key a sua chave. Aqui Iterator::rewind regressa a zero, Iterator::valid verifica se o índice existe e Iterator::next avança uma posição.
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]
Exemplos
<?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]