为什么 Simple XML 在设置变量后更新 PHP 变量?

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

我有一个 XML 文件:

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

还有我的 PHP 文件:

// 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"

为什么更新 XML 也会更改 $quantity$status 的值?它是否在每次调用变量 $quantity 时都重新加载文件(如果是这样,它看起来就像是一个函数而不是一个变量)?有没有办法防止这种情况/只加载一次文件?

这似乎是不寻常的行为 - 例如,在普通 PHP 中,如果我将变量 2 设置为变量 1,则在更新变量 1 时它不会更新变量 2:

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

为什么会这样?

这一行returns一个对象:

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

你可以通过调用 var_export($quantity); 看到 returns

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

因此,您使用的是引用而不是值类型。与以下相同:

$a = new stdClass();
$a->value = 'test';

$b = $a;
$b->value = 'changed';

echo $a->value; //Shows "changed"