PHP reference objects in loop loop

Suppose I have these classes:

class Foo { public $_data; public function addObject($obj) { $this->_data['objects'][] = $obj; } } class Bar { public $_data; public function __construct() { $this->_data['value'] = 42; } public function setValue($value) { $this->_data['value'] = $value; } } $foo = new Foo(); $bar = new Bar(); $foo->addObject($bar); foreach($foo->_data['objects'] as $object) { $object->setValue(1); } echo $foo->_data['objects'][0]->_data['value']; //42 

My actual code, very similar, uses ArrayAccess:

 foreach($this->_data['columns'] as &$column) { $filters = &$column->getFilters(); foreach($filters as &$filter) { $filter->filterCollection($this->_data['collection']); } } 

filterCollection changes the value in $ filter, but when you look at this $ object, this value is incorrect.

+4
source share
2 answers
 foreach($foo->_data['objects'] as &$object) { $object->setValue(1); } 

Pay attention to &

+9
source

Foreach works with a copy of the array. Use the object variable and before it.

foreach ($ foo → _ data ['objects'] as & $ object)

+1
source

Source: https://habr.com/ru/post/1338051/


All Articles