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.