如何在没有引用的情况下复制对象?
P粉805922437
P粉805922437 2023-08-24 10:51:49
0
2
481
<p>有据可查,PHP5 OOP 对象默认通过引用传递。如果这是默认的,在我看来,有一种非默认的方式可以在没有参考的情况下进行复制,如何??</p> <pre class="brush:php;toolbar:false;">function refObj($object){ foreach($object as &$o){ $o = 'this will change to ' . $o; } return $object; } $obj = new StdClass; $obj->x = 'x'; $obj->y = 'y'; $x = $obj; print_r($x) // object(stdClass)#1 (3) { // ["x"]=> string(1) "x" // ["y"]=> string(1) "y" // } // $obj = refObj($obj); // no need to do this because refObj($obj); // $obj is passed by reference print_r($x) // object(stdClass)#1 (3) { // ["x"]=> string(1) "this will change to x" // ["y"]=> string(1) "this will change to y" // }</pre> <p>此时我希望 <code>$x</code> 成为原始的 <code>$obj</code>,但当然不是。有什么简单的方法可以做到这一点还是我必须编写类似的代码</p>
P粉805922437
P粉805922437

全部回复(2)
P粉038161873

要复制对象,您需要使用对象克隆一个>.

要在您的示例中执行此操作,请执行以下操作:

$x = clone $obj;

请注意,对象可以使用 __clone() 定义自己的克隆行为,这可能会给您带来意想不到的行为,因此请记住这一点。

P粉713846879
<?php
$x = clone($obj);

所以它应该是这样的:

<?php
function refObj($object){
    foreach($object as &$o){
        $o = 'this will change to ' . $o;
    }

    return $object;
}

$obj = new StdClass;
$obj->x = 'x';
$obj->y = 'y';

$x = clone($obj);

print_r($x)

refObj($obj); // $obj is passed by reference

print_r($x)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板