dtdt0454 2011-02-02 06:23
浏览 38
已采纳

Foreach循环中的PHP参考对象

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.

  • 写回答

2条回答 默认 最新

  • dongmin4052 2011-02-02 06:27
    关注
    foreach($foo->_data['objects'] as &$object) {
        $object->setValue(1);
    }
    

    Notice the &

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?