你如何在 PHP 中显式地创建一个变量的副本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4777931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 14:20:15  来源:igfitidea点击:

How do you explicitly create a copy of a variable in PHP?

phpvariablesreference

提问by DisgruntledGoat

I have an array of stdClass objects. When I assign one to a variable, it is not copying the variable but instead referencing the original variable. My code is like this:

我有一个 stdClass 对象数组。当我给一个变量赋值时,它不是复制变量,而是引用原始变量。我的代码是这样的:

for ( $i = 0, $len = count($rows); $i < $len; $i++ )
{
    $row = $rows[$i];
    echo $rows[$i]->games;
    $row->games = 'test';
    echo $rows[$i]->games;
}

The first echo outputs the normal value, but the second echo outputs "test". Even though I am setting the property on $row(which should be copied), it's actually setting it on the original array element.

第一个回声输出正常值,但第二个回声输出“测试”。即使我将属性设置为$row(应该复制),它实际上是在原始数组元素上设置它。

Why is this, and how do I actually create a copy, so that modifying the copy doesn't modify the original?

为什么会这样,我如何实际创建副本,以便修改副本不会修改原始副本?

回答by Pekka

Use the clonekeyword.

使用clone关键字。

$copy = clone $object;

important to note:

重要的是要注意:

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.

克隆对象时,PHP 5 将执行对象所有属性的浅拷贝。任何引用其他变量的属性都将保持引用。

it comes with a nice magic method:

它带有一个很好的魔法方法:

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.

克隆完成后,如果定义了 __clone() 方法,则将调用新创建的对象的 __clone() 方法,以允许更改任何必要的属性。