We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Foreach loop update object by reference

When i tried following loop with reference, i got error.

foreach($category->posts as &$post)
{
    $post->custom = value;
}

Error

Fatal error: An iterator cannot be used with foreach by reference in

How can i modify the object with keep it and without creating new array?

Thanks

$category->posts is not an array.



58.1k
Accepted
answer

I solved with afterFetch method on model like following:

public function afterFetch()
{       
    $this->custom = "Hello World";
}