-2

我想使用 __clone() 来制作类对象的副本,然后我想打印该副本对象。这是代码:

<?php
class Test {

    public static $counter = 0;
    public $id;
    public $other;


    public function __construct(){ 
       $this->id = self::$counter++;

    }

    public function __clone()
    {
       $this->other = $that->other;
       $this->id = self::$counter++;
    }
}

$obj = new Test();
$copy = clone $obj;
print_r($copy);
?>
4

2 回答 2

3

Instead of

$copy = $obj->__clone();

You should use

$copy = clone $obj;

The __clone() method is called when you call clone

于 2013-07-25T12:30:12.293 回答
2

First of all, you do not clone an object by directly calling its __clone method. You should use the clone language construct, like this:

$new = clone $old;

That will call your __clone method for you to do any additional work after the object has been cloned.

Something to note: In PHP, objects are assigned by reference. What this means is that if you clone an object A which has a variable pointing to an object B, modifying B on the original will affect the clone, and vice-versa.

The __clone method allows you to react when a clone is happening, so you can properly clone B as well. Like this:

class B { }

class A {
    public $b;

    public function __construct() {
        $this->b = new B();
    }

    public function __clone() {
        $this->b = clone $b;
    }
}

$a = new A();
$c = clone $a;

// now you can safely modify $c->b without worrying about $a->b

Note that this nesting should go as deep as you want to receive copies for. Anything else will be copied by reference and can cause headaches down the line. General rule of thumb: be careful with clone.

于 2013-07-25T12:30:30.980 回答