Php 如何使用foreach循环中的函数更新属性?
我想更改Php 如何使用foreach循环中的函数更新属性?,php,xml,function,properties,parameters,Php,Xml,Function,Properties,Parameters,我想更改foreach循环中对象的某些属性: foreach ($object->array as $element) { $element['foo'] = $new_foo; $element['bar'] = $new_bar; } 我应该如何使用函数执行此操作?或者,我怎样才能用面向对象的方法做到这一点?我的代码不起作用,因为它只更改函数中$handle变量的值: function change_attribute(&$handle, $new_value
foreach
循环中对象的某些属性:
foreach ($object->array as $element) {
$element['foo'] = $new_foo;
$element['bar'] = $new_bar;
}
我应该如何使用函数执行此操作?或者,我怎样才能用面向对象的方法做到这一点?我的代码不起作用,因为它只更改函数中$handle
变量的值:
function change_attribute(&$handle, $new_value) {
$handle = $new_value;
}
foreach ($object->array as $element) {
change_attribute($element['foo'], $new_foo);
change_attribute($element['bar'], $new_bar);
}
function change_column_name(&$table, $index, $old, $new) {
if ($table->column[$index]['name'] == $old) {
$table->column[$index]['name'] = $new;
}
}
foreach ($xml->database[0]->table as $table) {
change_column_name($table, 1, 'old value', 'new value');
}
实际代码 它成功地更新了
$xml
对象,而没有引用数组元素(这将导致致命错误)。为什么我不能对这个函数做同样的操作
function change_attribute(&$handle, $old, $new) {
if ($handle == $old) {
$handle = $new;
}
}
foreach ($xml->database[0]->table as $table) {
change_attribute($table->column[1]['name'], 'old value', 'new value');
}
$xml
对象
这与var\u dump($xml->database[0]->table[0])
相同,只是后者是object(simplexmlement)#4(2)
您需要使用
&
将$element
作为参考,即
foreach ($object->array as &$element) {...}
如果没有它,您操作的是
$object->array
的副本,而不是数组本身。查看上的PHP文档。我必须将对象传递给函数,而不是类属性。不幸的是,后者必须在函数中硬编码:
function change_attribute(&$handle, $new_value) {
$handle = $new_value;
}
foreach ($object->array as $element) {
change_attribute($element['foo'], $new_foo);
change_attribute($element['bar'], $new_bar);
}
function change_column_name(&$table, $index, $old, $new) {
if ($table->column[$index]['name'] == $old) {
$table->column[$index]['name'] = $new;
}
}
foreach ($xml->database[0]->table as $table) {
change_column_name($table, 1, 'old value', 'new value');
}
在数组方面是正确的,但是不能以相同的方式使用对象,可能是因为它们是作为类属性嵌入到对象中的对象。另一种方法是让函数返回修改后的数组,并将其分配给首先调用函数的
$object
变量,从而取代了原来的内容。这比你的答案要贵,但它是有效的。PHP有引用。。。我们不妨使用它们:)@geogebrighton在你建议之前我也这样做了,正如例子#10中所写的,但这给了我一个致命的错误:迭代器不能与foreach by reference一起使用。问题可能在我的代码中的其他地方,今天我要检查它。@Gergő同时,你最好使用我的建议,然后哈哈。不,说真的,很贵。把它当作最后的手段或节省时间。@Gergő不知道为什么会这样。请看以下示例:。能否添加var\u dump($object->array)的输出你的问题是什么?
function change_column_name(&$table, $index, $old, $new) {
if ($table->column[$index]['name'] == $old) {
$table->column[$index]['name'] = $new;
}
}
foreach ($xml->database[0]->table as $table) {
change_column_name($table, 1, 'old value', 'new value');
}