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

标签 php variables reference

我有一组 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/

相关文章:

php - imagecreatefromweb 导致无法捕获的 fatal error

php - 按类别(术语)过滤 WooCommerce $order 商品

.net - 在 VB.NET 中将变量声明为 Byte 时出现的问题

reference - 为什么 find 闭包的参数需要两个 & 符号?

使用 neo4j 的 PHP 多步表单

android - 将 TextView 设置为分贝强度的字符串 - Android Studio

r - 如何评估 R 中带有变量的表达式?

c++ - 在 C++ 线程中,初始化引用

c++ - 如何在 C++ 中解释 "const int *const & variable"

php - Mysqli fetch_assoc() 循环与 Mysqli fetch_all() 数据库加载?