如何在PHP中创建对象的副本? [英] How do I create a copy of an object in PHP?
问题描述
似乎在PHP对象通过引用传递。即使赋值运算符似乎没有创建对象的副本。
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中的'clone'对象:
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中创建对象的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!