Does it make any difference if i copy object by simply assign it to another object instead of开发者_StackOverflow社区 clone it?
If you simple assign it, like:
$obj2 = $obj;
then you don't copy the object. You copy the reference to the object. Thus, $obj2
and $obj
point to the same object.
See also Objects and references
Example:
class A {
public $foo = 'bar';
}
$obj = new A();
$obj2 = $obj;
$obj2->foo = 'foo too';
echo $obj->foo . PHP_EOL;
$obj = new A();
$obj2 = clone($obj);
$obj2->foo = 'foo too';
echo $obj->foo . PHP_EOL;
prints
foo too
bar
DEMO
In addition to Felix Kling's answer, using clone enables usage of __clone() magic method.
class Obj{
public $cloned = 0;
public function __clone(){
$this->cloned++;
}
}
$obj1 = new Obj();
$obj2 = $obj1;
echo 'Times cloned: ' . $obj2->cloned; // returns 'Times cloned: 0'
var_dump($obj2 === $obj1); // true
$obj3 = clone $obj1;
echo 'Times cloned: ' . $obj3->cloned; // returns 'Times cloned: 1'
var_dump($obj3 === $obj1); // false
精彩评论