This is not Symfony's "fault". This is a misunderstanding of how to iterate over an object. There are several ways to handle this for your use case. Here are some
Use a foreach!
Your PersistentCollection
implements Collection
which implements IteratorAggregate
which implements Traversable
(long way heh?).
An object which implements interface Traversable
can be used in a foreach
statement.
IteratorAggregate
forces you to implement one method getIterator
which must return an Iterator
. This last also implements Traversable
interface.
Usage of an iterator
Iterator
interface forces your object to declare 5 methods in order to be used by a foreach
class MyCollection implements Iterator
{
protected $parameters = array();
protected $pointer = 0;
public function add($parameter)
{
$this->parameters[] = $parameter;
}
/**
* These methods are needed by Iterator
*/
public function current()
{
return $this->parameters[$this->pointer];
}
public function key()
{
return $this->pointer;
}
public function next()
{
$this->pointer++;
}
public function rewind()
{
$this->pointer = 0;
}
public function valid()
{
return array_key_exists($this->pointer, $this->parameters);
}
}
You can use any class which implements Iterator
it like this - Demo file
$coll = new MyCollection;
$coll->add('foo');
$coll->add('bar');
foreach ($coll as $key => $parameter) {
echo $key, ' => ', $parameter, PHP_EOL;
}
Use iterator with a while
In order to use this class like a foreach. Methods should be called this way - Demo file
$coll->rewind();
while ($coll->valid()) {
echo $coll->key(), ' => ', $coll->current(), PHP_EOL;
$coll->next();
}
foreach($zooAnimals as $animal)
?$zooAnimals
is not aarray()
!is_array($zooAnimals); // false
foreach
) over an object.