SPL Iterators Mixing

I found myself again standing in the shoulder of giants. I got some hints on how I would be able to mixin some of the features that several iterators interfaces and implementations were offering me. So here is the code:

These two examples below are usages for implementing similar things. I went for the first since it was what I wanted.

class PlayerCollection implements IteratorAggregate
{
    protected $players;
 
    public function __construct() {
        $this->players = new ArrayIterator();
    }
 
    public function add(Player $player) {
        $this->players[] = $player;
    }
 
    public function first() {
        return $this->players[0];
    }
 
    public function getIterator() {
        return new InfiniteIterator($this->players);
    }
}
 
$p1 = new Player("foo");
$p2 = new Player("bar");
$p3 = new Player("baz");
 
$pc = new PlayerCollection();
$pc->add($p1);
$pc->add($p2);
 
/*
foreach ($pc as $p) {
    echo $p->symbol;
}
*/
 
$pc->add($p3);
 
/*
foreach ($pc as $p) {
    echo $p->symbol;
}
*/
 
highlight_file(__FILE__);
<?php
 
$array = array(1, 2, 3);
$arr_it = new ArrayIterator($array);
 
$inf = new InfiniteIterator ($arr_it);
for ($i = 0; $i < 10; $i++) {
	echo $inf->current(); $inf->next(); 
}
 
echo "<br/><br/>";
 
// Add 4 to it
$arr_it[] = 4;
 
for ($i = 0; $i < 10; $i++) {
	echo $inf->current(); $inf->next(); 
}

Leave a Reply

Your email address will not be published. Required fields are marked *