PHP:是否可以通过ref将xml节点传递给函数并进行更改?

时间:2014-03-03 16:42:45

标签: php xml simplexml byref

我希望通过ref将xml节点传递给函数,并在函数内进行更改。但似乎节点的价值不能以这种方式改变。

例如:

<?php
$str = '<data><name>foo</name></data>';
$xml = simplexml_load_string($str);

test($xml->name);

echo $xml->name; //I expect it should be 'bar', but it is still 'foo'.

function test(&$node){  //it makes no difference if a '&' is added or not.
    $node = 'bar';
}
?>

或者如果我在这里弄错了?

1 个答案:

答案 0 :(得分:1)

您在那里犯了一个小错误:您正在将字符串'bar'分配给变量引用$node,即使用字符串替换目前为止由该变量命名的对象(id)值。相反,您需要将该对象保留在该变量中,并仅更改该SimpleXMLElement的节点值。这是通过所谓的自引用

完成的
function test(&$node) {
    $node[0] = 'bar';
}

如您所见,这与在该节点上添加[0]不同。实际上不需要&,因为对象不需要通过引用传递。另外你也应该提示类型:

function test(SimpleXMLElement $node) {
    $node[0] = 'bar';
}

就是这样,请参阅演示:https://eval.in/108589

为了更好地理解这个SimpleXMLElement自引用背后的魔力,请继续阅读following answer which is about removing a node only by it's variable,它类似于设置它的值。请注意SimpleXMLElement魔法有关,因此第一眼看上去可能不太直观。