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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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 php.net/manual/class.traversable.php).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.