2

I wish to pass a xml node to a function by ref, and make change within the function. But seem the node's value couldn't be changed in this way.

Example:

<?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';
}
?>

Or if I made mistake here?

1 Answers1

1

You made a small mistake there: You are assigning the string 'bar' to the variable reference $node, that is replacing the object (id) value named by that variable so far with a string. Instead you need to retain the object in that variable and only change the node-value of that SimpleXMLElement. That is done with a so called self-reference:

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

As you can see, this differs by adding [0] on that node. The & is not needed here actually as objects do not need to be passed by reference. Additionally you should hint the type as well:

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

And that's it, see the Demo: https://eval.in/108589 .

To better understand the magic behind this SimpleXMLElement self-reference here, please continue to read the following answer which is about removing a node only by it's variable which is similar to setting the value of it. Take note that SimpleXMLElement is with magic, so things might not be intuitive on first sight.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836