Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Reference Objects in Foreach Loop

Lets say 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 is this, very similar, uses ArrayAccess:

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

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

like image 487
chris Avatar asked Dec 22 '22 18:12

chris


2 Answers

foreach($foo->_data['objects'] as &$object) {
    $object->setValue(1);
}

Notice the &

like image 159
BlueDog Avatar answered Jan 08 '23 14:01

BlueDog


Foreach operates on a copy of the array. Use an & before the object variable.

foreach($foo->_data['objects'] as &$object)
like image 20
user225879 Avatar answered Jan 08 '23 13:01

user225879