Why does Simple XML update PHP variables after they've been set?

I have an XML file:

<?xml version="1.0"?>
<xml>
  <node>
    <child1>
      <value1>20.6</value1>
      <value2>Progress</value2>
    </child1>
  </node>
</xml>

And my PHP file:

// load the document
$xml = simplexml_load_file('file.xml');

// get values
$quantity = $xml->node->child1->value1;
$status = $xml->node->child1->value2;

echo $quantity . " / " . $status;  // results in "20.6 / Progress"

// new values
$newqty = 43;
$newstat = "Stopped";

// update
$xml->node->child1->value1 = $newqty;
$xml->node->child1->value2 = $newstat;

// save the updated document
$info->asXML('file.xml');

echo $quantity . " / " . $status;  // results in "43 / Stopped"

Why does updating the XML also change the value of $quantity and $status? Does it reload the file every time the variable $quantity is called (would seem as if it's acting as a function rather than a variable if so)? And is there a way to prevent this / only load the file once?

This seems unusual behaviour - for instance, in plain PHP, if I set a variable 2 to variable 1, it won't update variable 2 when variable 1 is updated:

// get values
$value1 = "Testing";
$value2 = $value1;
$value1 = "New test result";
echo $value2; // will result in "Testing"

Why does this happen?

1 answer

  • answered 2021-05-14 13:45 Chris Haas

    This line returns an object:

    $quantity = $xml->node->child1->value1

    You can see that by calling var_export($quantity); which returns

    SimpleXMLElement::__set_state(array(
       0 => '20.6',
    ))
    

    Because of this, you are working with a reference and not a value type. It is the same as the following:

    $a = new stdClass();
    $a->value = 'test';
    
    $b = $a;
    $b->value = 'changed';
    
    echo $a->value; //Shows "changed"