PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Comparaison d'objets> <Mot-clé "final"
Last updated: Fri, 05 Sep 2008

view this page in

Clonage d'objets

Le fait de créer une copie d'un objet possédant exactement les mêmes propriétés n'est pas toujours le comportement que l'on souhaite. Un bon exemple pour illustrer le besoin d'un constructeur de copie : si vous avez un objet qui représente une fenêtre GTK et que l'objet contient la ressource représentant cette fenêtre GTK, lorsque vous créez une copie vous pouvez vouloir créer une nouvelle fenêtre avec les mêmes propriétés mais que le nouvel objet contienne une ressource représentant la nouvelle fenêtre.

Une copie d'objet est créée en utilisant le mot-clé clone (qui fait appel à la méthode __clone() de l'objet, si elle a été définie). La méthode __clone() d'un objet ne peut être appelée directement.

<?php

$copie_d_objet = clone $objet;

?>

Lorsqu'un objet est cloné, PHP 5 effectue une copie superficielle de toutes les propriétés de l'objet. Toutes les propriétés qui sont des références à d'autres variables demeureront des références. Si une méthode __clone() est définie, la méthode __clone() du nouvel objet sera appelée pour permettre à chaque propriété qui doit l'être d'être modifiée.

Exemple #1 Exemple de duplication d'objets

<?php
class SubObject 
{
  static 
$instances 0;
  public 
$instance;

  public function 
__construct() {
    
$this->instance = ++self::$instances;
  }

  public function 
__clone() {
    
$this->instance = ++self::$instances;
  }
}

class 
MyCloneable 
{
  public 
$objet1;
  public 
$objet2;

  function 
__clone() 
  {    
    
// Force la copie de this->object, sinon
    // il pointera vers le même objet.
    
$this->object1 = clone $this->object1;
  }
}

$obj = new MyCloneable();

$obj->object1 = new SubObject();
$obj->object2 = new SubObject();

$obj2 = clone $obj;


print(
"Objet original :\n");
print_r($obj);

print(
"Objet cloné :\n");
print_r($obj2);

?>

L'exemple ci-dessus va afficher :

Object original :
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)
Object cloné :
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

    [object2] => SubObject Object
        (
            [instance] => 2
        )

)


Comparaison d'objets> <Mot-clé "final"
Last updated: Fri, 05 Sep 2008
 
add a note add a note User Contributed Notes
Clonage d'objets
Jim Brown
20-Jul-2008 01:34
Regarding the generic deep __clone() example provided by david ashe at metabin:

If your object has a variable that stores an array of objects, that particular __clone() example will NOT perform a deep copy on your array of objects.
alex dot offshore at gmail dot com
19-May-2008 01:23
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
crrodriguez at suse dot de
13-Mar-2008 07: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.
Hayley Watson
18-Dec-2007 01: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);
david ashe at metabin
02-Dec-2007 08: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);
            }
        }
    }
tomi at cumulo dot fi
13-Nov-2007 01: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.
muratyaman at gmail dot com
08-Oct-2007 05: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..
Alexey
08-Feb-2007 05: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.
MakariVerslund at gmail dot com
22-Jan-2007 02: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.
jorge dot villalobos at gmail dot com
31-Mar-2005 02: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.

Comparaison d'objets> <Mot-clé "final"
Last updated: Fri, 05 Sep 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites