Motivo per l'utilizzo del clone è che PHP quando si lavora con oggetto restituisce sempre oggetto come riferimento, non come copia.
È per questo che quando si passa oggetto a una funzione non è necessario specificare con & (di riferimento):
function doSomethingWithObject(MyObject $object) { // it is same as MyObject &object
...
}
Quindi, al fine di ottenere l'oggetto copiare è necessario utilizzare clone parola chiave Questo è un esempio di come gli oggetti vengono gestiti da PHP e che cosa fa il clone:
class Obj {
public $obj;
public function __construct() {
$this->obj = new stdClass();
$this->obj->prop = 1; // set a public property
}
function getObj(){
return $this->obj; // it returns a reference
}
}
$obj = new Obj();
$a = $obj->obj; // get as public property (it is reference)
$b = $obj->getObj(); // get as return of method (it is also a reference)
$b->prop = 7;
var_dump($a === $b); // (boolean) true
var_dump($a->prop, $b->prop, $obj->obj->prop); // int(7), int(7), int(7)
// changing $b->prop didn't actually change other two object, since both $a and $b are just references to $obj->obj
$c = clone $a;
$c->prop = -3;
var_dump($a === $c); // (boolean) false
var_dump($a->prop, $c->prop, $obj->obj->prop); // int(7), int(-3), int(7)
// since $c is completely new copy of object $obj->obj and not a reference to it, changing prop value in $c does not affect $a, $b nor $obj->obj!
fonte
2012-08-30 11:12:24
Il [modello Prototype design] (http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612/ref = sr_1_1) è anche un buon caso d'uso. – pce