arrays - PHP An iterator cannot be used with foreach by reference -


i have object implements iterator , holds 2 arrays: "entries" , "pages". whenever loop through object, want modify entries array error an iterator cannot used foreach reference see started in php 5.2.

my question is, how can use iterator class change value of looped object while using foreach on it?

my code:

//$flavors = instance of class: class paginatedresultset implements \iterator {     private $position = 0;      public $entries = array();     public $pages = array();      //...iterator methods... }  //looping //throws error here foreach ($flavors &$flavor) {     $flavor = $flavor->stdclassforapi(); } 

the reason $flavors not instance of class , instead simple array. want able modify array regardless of type is.

i tried creating iterator used:

public function &current() {     $element = &$this->array[$this->position];     return $element; } 

but still did not work.

the best can recommend implement \arrayaccess, allow this:

foreach ($flavors $key => $flavor) {     $flavors[$key] = $flavor->stdclassforapi(); } 

using generators:

updating based on marks comment on generators, following allow iterate on results without needing implement \iterator or \arrayaccess.

class paginatedresultset {     public $entries = array();      public function &iterate()     {         foreach ($this->entries &$v) {             yield $v;         }     } }  $flavors = new paginatedresultset(/* args */);  foreach ($flavors->iterate() &$flavor) {     $flavor = $flavor->stdclassforapi(); } 

this feature available in php 5.5.


Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -