mardi 24 mars 2015

Cleanly using PHP Iterator class in Loops - calling first element


I have implemented the Iterator class in PHP and built the follow mandatory methods as follows



class I implements Iterator
{

private $a = [];

function __construct(array $a)
{
$this->a = $a;
}


function current()
{
return current($this->a);
}


function next()
{
return next($this->a);
}


function previous()
{

}


function valid()
{
return key($this->a) !== null;
}


function rewind()
{
return reset($this->a);
}


function key()
{
return key($this->a);
}

}


When constructing a loop and calling our Iterator, I have noticed to get the first element is a problem.


Example



$a = ['a','b','c','d'];

$b = ['twelve', 'eleven', 'ten', 'nine'];

$I = new I($a);


foreach($b as $k => $v)
echo $I->next();


I want the Iterator to output starting from a, but what happens is our Iterator starts by outputting b.


We can get ideal output by writing some code like the following



for($i = 0; $i < count($a); $i++)
{
if($i == 0)
echo $i->current();
else
echo $i->next();
}


However the above workaround is not efficent and not very clean at all.


Am I implementing this class wrong? Or am I looping/using it wrong?





Aucun commentaire:

Enregistrer un commentaire