我有一组 stdClass 对象。当我将一个分配给一个变量时,它不是复制变量而是引用原始变量。我的代码是这样的:
for ( $i = 0, $len = count($rows); $i < $len; $i++ )
{
$row = $rows[$i];
echo $rows[$i]->games;
$row->games = 'test';
echo $rows[$i]->games;
}
第一个echo输出的是正常值,但是第二个echo输出的是“test”。即使我在 $row
上设置属性(应该复制),它实际上是在原始数组元素上设置它。
这是为什么,我该如何实际创建一个副本,以便修改副本不会修改原始文件?
最佳答案
使用 clone
关键字。
$copy = clone $object;
注意事项:
When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.
它带有一个很好的魔术方法:
Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.
关于php - 如何在 PHP 中显式创建变量的副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4777931/