How do I create a copy of an object in PHP?(如何在 PHP 中创建对象的副本?)
问题描述
似乎在 PHP 中对象是通过引用传递的.甚至赋值运算符似乎也没有创建 Object 的副本.
It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.
这是一个简单的、人为的证明:
Here's a simple, contrived proof:
<?php
class A {
public $b;
}
function set_b($obj) { $obj->b = "after"; }
$a = new A();
$a->b = "before";
$c = $a; //i would especially expect this to create a copy.
set_b($a);
print $a->b; //i would expect this to show 'before'
print $c->b; //i would ESPECIALLY expect this to show 'before'
?>
在这两种打印情况下,我都得到了之后"
In both print cases I am getting 'after'
那么,我如何将 $a 通过值而不是引用传递给 set_b()?
So, how do I pass $a to set_b() by value, not by reference?
推荐答案
在 PHP 5+ 中,对象是通过引用传递的.在 PHP 4 中,它们是按值传递的(这就是为什么它在运行时通过引用传递,这已被弃用).
In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).
您可以使用 PHP5 中的克隆"运算符来复制对象:
You can use the 'clone' operator in PHP5 to copy objects:
$objectB = clone $objectA;
此外,它只是通过引用传递的对象,而不是您在问题中所说的所有内容......
Also, it's just objects that are passed by reference, not everything as you've said in your question...
这篇关于如何在 PHP 中创建对象的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 PHP 中创建对象的副本?
基础教程推荐
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01