Remember that in PHP 5 ALL objects are assigned BY REFERENCE.
<?php
function foo($a) // notice that '&' near $a is missing
{
$a['bar'] = 10;
}
$x = array('bar' => 0); // built-in array() is not an object
$y = new ArrayObject(array('bar' => 0));
echo "\$x['bar'] == ${x['bar']};\n\$y['bar'] == ${y['bar']};\n\n";
foo($x);
foo($y);
echo "\$x['bar'] == ${x['bar']};\n\$y['bar'] == ${y['bar']};\n";
?>
Output:
$x['bar'] == 0;
$y['bar'] == 0;
$x['bar'] == 0;
$y['bar'] == 10;
Hope this will be useful.
By the way, to determine whether the variable is compatible with ArrayAccess/ArrayObject see http://php.net/manual/en/function.is-array.php#48083
Objekte klonen
Eine Kopie eines Objektes mit vollständig replizierten Eigenschaften zu erzeugen ist nicht immer das gewünschte Verhalten. Ein gutes Beispiel für die Notwendigkeit von Kopierkonstruktoren ist ein Objekt, welches ein GTK Fenster repräsentiert und dieses Objekt enthält die Resource des GTK Fensters. Wenn Sie ein Duplikat dieses Objektes erzeugen, könnten Sie ein neues Fenster mit gleichen Eigenschaften erzeugen wollen und das neue Objekt soll die Resource des neuen Fensters speichern. Ein weiteres Beispiel ist ein Objekt, welches eine Referenz auf ein anderes Objekt, das es benutzt, hält und wenn das Vaterobjekt repliziert wird, will man eine neue Instanz dieses anderen Objektes erzeugen, damit das Replikat eine eigene Kopie besitzt.
Eine Objektkopie wird durch die Nutzung des clone Schlüsselwortes (welches wenn möglich die __clone() Methode des Objektes aufruft) erzeugt. Die __clone() Methode eines Objektes kann nicht direkt aufgerufen werden.
$kopie_des_objektes = clone $objekt;
Wenn ein Objekt geklont wird, wird PHP 5 eine seichte Kopie der Eigenschaften des Objektes durchführen. Alle Eigenschaften, die Referenzen auf andere Variablen sind, werden Referenzen bleiben. Falls eine __clone() Methode definiert ist, wird die __clone() Methode des frisch erzeugten Objektes aufgerufen, um alle notwendigen Eigenschaften die geändert werden müssen ändern zu können.
Beispiel #1 Ein Objekt klonen
<?php
class SubObject
{
static $instanzen = 0;
public $instanz;
public function __construct() {
$this->instanz = ++self::$instanzen;
}
public function __clone() {
$this->instanz = ++self::$instanzen;
}
}
class MyCloneable
{
public $objekt1;
public $objekt2;
function __clone()
{
// Erzwinge eine Kopie von this->object,
// andernfalls wird es auf das selbe Objekt zeigen
$this->objekt1 = clone $this->objekt1;
}
}
$obj = new MyCloneable();
$obj->objekt1 = new SubObject();
$obj->objekt2 = new SubObject();
$obj2 = clone $obj;
print("Original Objekt:\n");
print_r($obj);
print("geklontes Objekt:\n");
print_r($obj2);
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
Original Object: MyCloneable Object ( [object1] => SubObject Object ( [instanz] => 1 ) [object2] => SubObject Object ( [instanz] => 2 ) ) Cloned Object: MyCloneable Object ( [objekt1] => SubObject Object ( [instanz] => 3 ) [objekt2] => SubObject Object ( [instanz] => 2 ) )
Objekte klonen
19-May-2008 03:23
12-Mar-2008 10:52
Keep in mind that since PHP 5.2.5, trying to clone a non-object correctly results in a fatal error, this differs from previous versions where only a Warning was thrown.
20-Feb-2008 11:55
I sorely apologize if this point seems to be obvious, but being slightly impatient, I do not care to know how many times I overlooked this.
For God's sake, notice the lack of the '$' in front of objects when referencing them with '$this'. Not included, this allows class variables to be properly addressed.
eg, $this->$a, will NOT work properly with clone(), but this will: $this->a.
17-Dec-2007 03:51
It should go without saying that if you have circular references, where a property of object A refers to object B while a property of B refers to A (or more indirect loops than that), then you'll be glad that clone does NOT automatically make a deep copy!
<?php
class Foo
{
var $that;
function __clone()
{
$this->that = clone $this->that;
}
}
$a = new Foo;
$b = new Foo;
$a->that = $b;
$b->that = $a;
$c = clone $a;
echo 'What happened?';
var_dump($c);
02-Dec-2007 10:18
Here is a function to clone all of the objects automatically
(useful if you use a base class that has this method)
function __clone(){
foreach($this as $name => $value){
if(gettype($value)=='object'){
$this->$name= clone($this->$name);
}
}
}
13-Nov-2007 03:57
It should be noticed that __clone() does not allow you to return a value. Basically the idea is that you implement this magic method only when you want to execute operations inside the cloned object, immediately prior to the cloning. In this way __clone() is similar to the default destructor (__destruct()), in that it executes code right before the object is destroyed.
08-Oct-2007 07:43
I think this is a bit awkward:
<?php
class A{
public $aaa;
}
class B{
public $a;
public $bbb;
function __clone(){
$this->a = clone $this->a;//clone MANUALLY!!!
}
}
$b1 = new B();
$b1->a = new A();
$b1->a->aaa = 111;
$b1->bbb = 1;
$b2 = clone $b1;
$b2->a->aaa = 222;//BEWARE!!
$b2->bbb = 2;//no problem on basic types
var_dump($b1); echo '<br />';
var_dump($b2);
/*
OUTPUT BEFORE implementing the function __clone()
object(B)#2 (3) { ["a"]=> object(A)#3 (1) { ["aaa"]=> int(222) } ["bbb"]=> int(1) }
object(B)#4 (3) { ["a"]=> object(A)#3 (1) { ["aaa"]=> int(222) } ["bbb"]=> int(2) }
OUTPUT AFTER implementing the function __clone()
object(B)#1 (3) { ["a"]=> object(A)#2 (1) { ["aaa"]=> int(111) } ["bbb"]=> int(1) }
object(B)#3 (3) { ["a"]=> object(A)#4 (1) { ["aaa"]=> int(222) } ["bbb"]=> int(2) }
*/
?>
Whenever we use another class inside, we must clone it manually. If you have 10s of classes related, this is rather tedious. I don't want to even think about classes dynamically populated with other objects. Be careful when designing your classes! You should look after your objects all the time! This major change on PHP5 vs PHP4 regarding "references" definitely has very good performance improvements but comes with very dangerous side effects as well..
13-Jun-2007 01:00
In PHP4 the clone keyword isn't defined, if you want a compatible code (using a copy of an object) - use this fix:
$c = (PHP_VERSION < 5) ? $b : clone($b);
It is possible cause php checks function existence just before its calling.
08-Feb-2007 07:18
To implement __clone() method in complex classes I use this simple function:
function clone_($some)
{
return (is_object($some)) ? clone $some : $some;
}
In this way I don't need to care about type of my class properties.
21-Jan-2007 04:30
I ran into the same problem of an array of objects inside of an object that I wanted to clone all pointing to the same objects. However, I agreed that serializing the data was not the answer. It was relatively simple, really:
public function __clone()
{
foreach ($this->varName as &$a)
{
foreach ($a as &$b)
{
$b = clone $b;
}
}
}
Note, that I was working with a multi-dimensional array and I was not using the Key=>Value pair system, but basically, the point is that if you use foreach, you need to specify that the copied data is to be accessed by reference.
22-Sep-2006 07:20
Copying objects with
<?php
public function copy()
{
$serialized_contents = serialize($this);
return unserialize($serialized_contents);
}
?>
is a pretty dangerous thing. What if your objects hold references to very large shared objects? They all get copied as well. Serializing objects may break database connections and references. What you probably want to do is implement a proper __clone() method for each of your classes so that each object in your tree gets to decide what subobjects need to be copied and which ones should better remain untouched.
regards
felix
03-Aug-2006 01:47
I noticed when trying to clone a series of objects in a loop and and adding them to an array, the objects were still passed by reference, so all objects took the same value as the last object cloned and added to the array.
The solution was to use the copy function as below which truly clones objects.
Here is an example:
<?php
$temp = new $this->_doname;
foreach($rows as $id=>$row) {
$do = clone $temp;
$do->load($id);
$this->_dataobjects[]= clone $do;
}
?>
This results in every object having the same value.
However using:
<?php
$this->_dataobjects[]= $this->copy($do);
?>
with
<?php
public function copy()
{
$serialized_contents = serialize($this);
return unserialize($serialized_contents);
}
?>
Actually produces the expected result.
Paul Bain
16-May-2006 04:49
As jorge dot villalobos at gmail dot com pointed out, the "__clone is NOT an override".
However, if one needs a true copy of an object (which has real copies of all subobjects too, not references), one can define a class method such as this to the object-to-be-cloned:
public function copy()
{
$serialized_contents = serialize($this);
return unserialize($serialized_contents);
}
The method makes a string representation of the object's contents (including subobjects), which can then be unserialized back to an object.
The method usage is simple:
$original_object = new MyCloneable(); //can have sub objects
$copied_object = $original_object->clone(); //only makes copies of the values, not references
With serialization, you surely don't have to worry about references, since serialized object is just simple text.
08-Feb-2006 08:02
Consider this:
function myfunc()
{
$A = new myobject(); // Create another mysql connection
$A->method1(); // Runs a query (works)
}
$A = new myobject(); // Create a mysql connection
myfunc();
$A->method1(); // This query fails! Possible because leaving the function has closed the connection.
Conclusion: Declaration of objects within and outside a function WITH THE SAME NAME, will affect each other. Do not relay on the rules of scope.
Take care when using recursive structures!!
It took me a long time to figure out.
30-Mar-2005 03:29
I think it's relevant to note that __clone is NOT an override. As the example shows, the normal cloning process always occurs, and it's the responsibility of the __clone method to "mend" any "wrong" action performed by it.
