Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

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

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

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

$copy_of_object = clone $object;

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

Пример 19-30. Клонирование объекта

<?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
Клонирование объектов
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..
Mr.KTO
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.
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.
felix gilcher
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
paul at accessdesigns dot org dot uk
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
olle dot remove_this dot suni at rdnsoftware dot com
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.
ove at junne dot dk
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.
markus dot amsler at oribi dot org
20-Jun-2005 06:14
For php4 you can use the clone method from the PEAR PHP_Compat package (http://pear.php.net/package/PHP_Compat).
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.

 
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com
Z058440144362 Z348613067571