Foreach 循环中的 PHP 引用对象
假设我有这些类:
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
我的实际代码是这样的,非常相似,使用 ArrayAccess:
foreach($this->_data['columns'] as &$column) {
$filters = &$column->getFilters();
foreach($filters as &$filter) {
$filter->filterCollection($this->_data['collection']);
}
}
filterCollection 更改 $filter 中的值,但是当您查看 $this 对象时,该值不正确。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
注意 &
Notice the &
Foreach 对数组的副本进行操作。使用 &在对象变量之前。
Foreach operates on a copy of the array. Use an & before the object variable.
PHP 范例是对象(和资源)始终是引用,而其他类型(基本类型或数组)则被复制,因此 &运算符对对象没有影响(并且对资源没有意义,因为只有“特殊函数”,即外部库模块可以将它们作为参数),但允许通过引用传递其他类型的变量。
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.