【问题标题】:How to make a copy of an object without reference?如何在没有引用的情况下复制对象?
【发布时间】:2011-05-06 15:10:20
【问题描述】:

默认情况下 PHP5 OOP objects are passed by reference 是有据可查的。如果这是默认情况下,在我看来,没有默认的复制方式没有参考,如何??

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"
// }

此时我希望$x 成为原始$obj,但当然不是。有什么简单的方法可以做到这一点还是我必须编写一些代码like this

【问题讨论】:

    标签: php object pass-by-reference


    【解决方案1】:
    <?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)
    

    【讨论】:

    • 很高兴它有帮助。 lonesomeday 对 __clone() 魔术方法提出了一个很好的观点,一些类可能也在实现这一点,这一点值得注意。
    【解决方案2】:

    要复制一个对象,你需要使用object cloning

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

    $x = clone $obj;
    

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

    【讨论】:

    • 谢谢。你有一些有趣的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2010-11-25
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    相关资源
    最近更新 更多