<?php
/**
* Your classes should be traversable
* but you want to let the dev of the
* interface decide to use Iterator,
* IteratorAggregate or extending from
* a traversable class
*/
interface Fooable extends Traversable
{
public function foo();
}
/**
* Important order:
* Fooable needs to be set after another
* traversable interface
*/
class Foo1 implements IteratorAggregate, Fooable
{
private $foo;
public function __construct(array $foo = array())
{
$this->foo = $foo;
}
public function foo()
{
return 'Foo';
}
public function getIterator()
{
return new ArrayIterator($this->foo);
}
}
class Foo2 extends ArrayIterator implements Fooable
{
public function foo()
{
return 'Foo';
}
}
$foo1 = new Foo1(['Foo']);
$foo2 = new Foo2(['Foo']);
foreach ($foo1 as $value) {
echo $value . PHP_EOL;
}
foreach ($foo2 as $value) {
echo $value . PHP_EOL;
}