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-&开发者_Python百科gt;_data['collection']);
}
}
filterCollection changes a value in $filter, but when you look at the $this object, the value is not right.
foreach($foo->_data['objects'] as &$object) {
$object->setValue(1);
}
Notice the &
Foreach operates on a copy of the array. Use an & before the object variable.
foreach($foo->_data['objects'] as &$object)
PHP paradigm is that objects (and resources) are always references, while other types (base types or arrays) are copied, so the & operator has no effect on objects (and is meaningless on resources since only "special functions" i.e. external library modules can take them as parameters), but allows to pass variables of other types by reference.
精彩评论