Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

IteratorAggregate

Give a collection an external cursor by implementing getIterator(): Traversable.

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

Syntax

class Labels implements IteratorAggregate

Give a collection an external cursor by implementing getIterator(): Traversable. Returning a new iterator for each call supports independent nested or repeated passes. If the aggregate keeps returning the same generator, a second foreach over that already closed generator throws Exception. In the example IteratorAggregate::getIterator returns a fresh generator per call, so advancing the left cursor leaves the right cursor in place.

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

Examples

<?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);}

Result

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

Sources