Let an object loop as array with a foreach() by extending ArrayObject
-
14-06-2021 - |
Вопрос
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?
Решение
Use the SPL Iterator Interface see http://uk.php.net/manual/en/class.iterator.php for details
Другие советы
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
Не связан с StackOverflow