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

search for in the

Сравнение объектов> <Ключевое слово "final"
Last updated: Fri, 28 Nov 2008

view this page in

Клонирование объектов

Создание копии объекта с абсолютно идентичными свойствами не всегда является приемлемым вариантом. Хорошим примером необходимости копирования конструкторов может послужить ситуация, когда у вас есть объект, представляющий собой окно GTK и содержащий ресурс-идентификатор этого окна; когда вы создаете копию этого объекта, вам может понадобиться, чтобы копия объекта содержала ресурс-идентификатор нового окна. Другим примером может послужить ситуация, когда ваш объект содержит ссылку на какой-либо другой используемый объект и, когда вы создаёте копию ссылающегося объекта, вам нужно также создать новый экземпляр содержащегося объекта, так, чтобы копия объекта содержала собственный отдельный экземпляр содержащегося объекта.

Копия объекта создается с использованием вызова clone (который вызывает метод __clone() объекта, если это возможно). Вызов метода __clone() не может быть осуществлён непосредственно.

$copy_of_object = clone $object;

Когда программист запрашивает создание копии объекта, PHP 5 определит, был ли для этого объекта объявлен метод __clone() или нет. Если нет, будет вызван метод __clone(), объявленный по умолчанию, который скопирует все свойства объекта. Если метод __clone() был объявлен, создание копий свойств в копии объекта полностью возлагается на него. Для удобства, движок обеспечивает программиста функцией, которая импортирует все свойства из объекта-источника, так что программист может осуществить позначное копирование свойств и переопределять только необходимые.

Пример #1 Клонирование объекта

<?php
class MyCloneable {
   static 
$id 0;

   function 
MyCloneable() {
       
$this->id self::$id++;
   }

   function 
__clone() {
       
$this->address "Москва";
       
$this->id self::$id++;
   }
}

$obj = new MyCloneable();

$obj->name "Привет";
$obj->address "Самара";

print 
$obj->id "\n";

$obj_cloned = clone $obj;

print 
$obj_cloned->id "\n";
print 
$obj_cloned->name "\n";
print 
$obj_cloned->address "\n";
?>


add a note add a note User Contributed Notes
Клонирование объектов
cheetah at tanabi dot org
18-Nov-2008 05:15
Want deep cloning without too much hassle?

<?php
function __clone() {
    foreach(
$this as $key => $val) {
        if(
is_object($val)||(is_array($val))){
           
$this->{$key} = unserialize(serialize($val));
        }
    }
}
?>

That will insure any object, or array that may potentially contain objects, will get cloned without using recursion or other support methods.
wbcarts at juno dot com
02-Oct-2008 11:41
CLONED ARMIES? USE STATIC DATA

When I think of cloning, I always think of Star Wars "Cloned Army"... where the number of clones are in the hundreds of thousands. So far, I have only seen examples of one or two clones with either shallow, deep, or recursive references. My fix is to use the static keyword. With static, you choose the properties your objects share... and makes scaling up the number of so-called "clones" much easier.

<?php

class Soldier {
  public static
$status;           // this is the property I'm trying to clone

 
protected static $idCount = 0;   // used to increment ID numbers
 
protected $id;                   // each Soldier will have a unique ID

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

  public function
issueCommand($task) {
    switch(
$task){
      case
'Deploy Troops': self::$status = 'deploying'; break;
      case
'March Forward': self::$status = 'marching forward'; break;
      case
'Fire!': self::$status = 'shot fired'; break;
      case
'Retreat!': self::$status = 'course reversed'; break;
      default:
self::$status = 'at ease'; break;
    }
    echo
'COMMAND ISSUED: ' . $task . '<br>';
  }

  public function
__toString() {
    return
"Soldier[id=$this->id, status=" . self::$status . ']';
  }
}

# create the General and the Cloned Army
$general = new Soldier();
$platoon = array();
  for(
$i = 0; $i < 250; $i++) $platoon[] = new Soldier();

# issue commands, then check what soldiers are doing
$general->issueCommand('Deploy Troops');
echo
$general . '<br>';
echo
$platoon[223] . '<br>';
echo
$platoon[12] . '<br>';

$general->issueCommand('March Forward');
echo
$platoon[47] . '<br>';
echo
$platoon[163] . '<br>';

$general->issueCommand('Fire!');
echo
$platoon[248] . '<br>';
echo
$platoon[68] . '<br>';

$general->issueCommand('Retreat!');
echo
$platoon[26] . '<br>';
echo
$platoon[197] . '<br>';
?>

COMMAND ISSUED: Deploy Troops
  Soldier[id=1, status=deploying]
  Soldier[id=225, status=deploying]
  Soldier[id=14, status=deploying]

COMMAND ISSUED: March Forward
  Soldier[id=49, status=marching forward]
  Soldier[id=165, status=marching forward]

COMMAND ISSUED: Fire!
  Soldier[id=250, status=shot fired]
  Soldier[id=70, status=shot fired]

COMMAND ISSUED: Retreat!
  Soldier[id=28, status=course reversed]
  Soldier[id=199, status=course reversed]
Jim Brown
19-Jul-2008 03: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 03: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
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.
Hayley Watson
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);
david ashe at metabin
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);
            }
        }
    }
tomi at cumulo dot fi
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.
muratyaman at gmail dot com
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..
Alexey
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.
MakariVerslund at gmail dot com
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.
jorge dot villalobos at gmail dot com
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.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites