如何在PHP中显式创建变量的副本?

时间:2021-08-08 19:35:01

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.

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

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

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

1 个解决方案

#1


43  

Use the clone keyword.

使用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()方法,以允许任何需要更改的必要属性。

#1


43  

Use the clone keyword.

使用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()方法,以允许任何需要更改的必要属性。