Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / PHP

IteratorAggregate

Fornisce un cursore esterno alla raccolta con getIterator(): Traversable.

Versione: PHP 8.4; repository runtime, production runtime not attested

Sintassi

class Labels implements IteratorAggregate

Fornisce un cursore esterno alla raccolta con getIterator(): Traversable. Un iteratore nuovo per chiamata permette visite annidate e ripetute indipendenti. Se l’oggetto restituisce sempre lo stesso generatore, un secondo foreach sul generatore chiuso lancia Exception. Qui IteratorAggregate::getIterator restituisce un generatore nuovo a ogni chiamata, quindi avanzare il cursore sinistro non sposta il destro.

class Labels implements IteratorAggregate { public function getIterator(): Traversable { yield "a"=>1; yield "b"=>2; } }
$labels=new Labels(); $left=$labels->getIterator(); $right=$labels->getIterator(); $left->next();
echo json_encode([$left->current(),$right->current(),iterator_to_array($labels)]);
class Once implements IteratorAggregate { public function __construct(private Generator $g){} public function getIterator(): Traversable {return $this->g;} }
$once=new Once($labels->getIterator()); foreach($once as $v){} try{foreach($once as $v){}}catch(Exception $e){echo PHP_EOL,get_class($e);}
[2,1,{"a":1,"b":2}]
Exception

Esempi

<?php
class Labels implements IteratorAggregate { public function getIterator(): Traversable { yield "a"=>1; yield "b"=>2; } }
$labels=new Labels(); $left=$labels->getIterator(); $right=$labels->getIterator(); $left->next();
echo json_encode([$left->current(),$right->current(),iterator_to_array($labels)]);
class Once implements IteratorAggregate { public function __construct(private Generator $g){} public function getIterator(): Traversable {return $this->g;} }
$once=new Once($labels->getIterator()); foreach($once as $v){} try{foreach($once as $v){}}catch(Exception $e){echo PHP_EOL,get_class($e);}

Risultato

[2,1,{"a":1,"b":2}]
Exception

Fonti