3

So I have an object which contains a set of objects in a private data member. I can now loop it with a for loop by overriding the count() function of an ArrayObject and offsetGet($index), but I also want to loop it within a foreach loop.

What functions do I need to minimally extend to add this functionality?

shadyyx
  • 15,825
  • 6
  • 60
  • 95
Cas van Noort
  • 255
  • 3
  • 9

2 Answers2

3

Use the SPL Iterator Interface see http://uk.php.net/manual/en/class.iterator.php for details

Rufinus
  • 29,200
  • 6
  • 68
  • 84
2

AFAIK You can use directly foreach on ArrayObject:

$ao = new ArrayObject(array(1, 2, 3, 4));
$res = 0;
foreach($ao as $el) {
    $res += $el;
}
echo 'ArrayObject elements sum: '.$res;

SAMPLE: http://codepad.org/uQDGQ03A

shadyyx
  • 15,825
  • 6
  • 60
  • 95
  • 3
    An object can be used with a foreach loop when it a) is an array or b) implements the Traversable interface. ArrayObject implements this interface (see http://php.net/manual/class.traversable.php). – Niko Jun 15 '12 at 12:21