I want to perform some magic so that when I try to iterate over an object I will actually iterate over an array from within the object. Something like a getter for loops.
class A {
protected $array = [1,2,3];
public function __foriteration() {
return $this->array;
}
}
$a = new A;
foreach($a as $value) {
echo $value;
}
// output should be "123"
Not even sure that this is possible but I suspect I should be using ArrayObject but it is not very straightforward for me, I can't figure out how to make it do this.
Please note: I could define a getter method and loop over $a->getArray() but that is not what I want to do. Thank you.
Iteratorinterface. Have a look at the following link: php.net/manual/en/language.oop5.iterations.php