ΠšΠ»ΠΎΠ½ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ΠΎΠ²

Π‘ΠΎΠ·Π΄Π°Π½ΠΈΠ΅ ΠΊΠΎΠΏΠΈΠΈ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° с Π°Π±ΡΠΎΠ»ΡŽΡ‚Π½ΠΎ ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ‡Π½Ρ‹ΠΌΠΈ свойствами Π½Π΅ всСгда являСтся ΠΏΡ€ΠΈΠ΅ΠΌΠ»Π΅ΠΌΡ‹ΠΌ Π²Π°Ρ€ΠΈΠ°Π½Ρ‚ΠΎΠΌ. Π₯ΠΎΡ€ΠΎΡˆΠΈΠΌ ΠΏΡ€ΠΈΠΌΠ΅Ρ€ΠΎΠΌ нСобходимости копирования конструкторов ΠΌΠΎΠΆΠ΅Ρ‚ ΠΏΠΎΡΠ»ΡƒΠΆΠΈΡ‚ΡŒ ситуация, ΠΊΠΎΠ³Π΄Π° Ρƒ вас Π΅ΡΡ‚ΡŒ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚, ΠΏΡ€Π΅Π΄ΡΡ‚Π°Π²Π»ΡΡŽΡ‰ΠΈΠΉ собой ΠΎΠΊΠ½ΠΎ GTK ΠΈ содСрТащий рСсурс-ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ этого ΠΎΠΊΠ½Π°; ΠΊΠΎΠ³Π΄Π° Π²Ρ‹ создаётС копию этого ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°, Π²Π°ΠΌ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΏΠΎΠ½Π°Π΄ΠΎΠ±ΠΈΡ‚ΡŒΡΡ, Ρ‡Ρ‚ΠΎΠ±Ρ‹ копия ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° содСрТала рСсурс-ΠΈΠ΄Π΅Π½Ρ‚ΠΈΡ„ΠΈΠΊΠ°Ρ‚ΠΎΡ€ Π½ΠΎΠ²ΠΎΠ³ΠΎ ΠΎΠΊΠ½Π°. Π”Ρ€ΡƒΠ³ΠΈΠΌ ΠΏΡ€ΠΈΠΌΠ΅Ρ€ΠΎΠΌ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΏΠΎΡΠ»ΡƒΠΆΠΈΡ‚ΡŒ ситуация, ΠΊΠΎΠ³Π΄Π° ваш ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ содСрТит ссылку Π½Π° ΠΊΠ°ΠΊΠΎΠΉ-Π»ΠΈΠ±ΠΎ Π΄Ρ€ΡƒΠ³ΠΎΠΉ ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΠ΅ΠΌΡ‹ΠΉ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ ΠΈ, ΠΊΠΎΠ³Π΄Π° Π²Ρ‹ создаётС копию Ρ€ΠΎΠ΄ΠΈΡ‚Π΅Π»ΡŒΡΠΊΠΎΠ³ΠΎ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°, Π²Π°ΠΌ Π½ΡƒΠΆΠ½ΠΎ Ρ‚Π°ΠΊΠΆΠ΅ ΡΠΎΠ·Π΄Π°Ρ‚ΡŒ Π½ΠΎΠ²Ρ‹ΠΉ экзСмпляр этого Π΄Ρ€ΡƒΠ³ΠΎΠ³ΠΎ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°, Ρ‚Π°ΠΊ, Ρ‡Ρ‚ΠΎΠ±Ρ‹ копия ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°-ΠΊΠΎΠ½Ρ‚Π΅ΠΉΠ½Π΅Ρ€Π° содСрТала собствСнный ΠΎΡ‚Π΄Π΅Π»ΡŒΠ½Ρ‹ΠΉ экзСмпляр содСрТащСгося ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°.

Копия ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° создаётся с использованиСм ΠΊΠ»ΡŽΡ‡Π΅Π²ΠΎΠ³ΠΎ слова clone (ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π²Ρ‹Π·Ρ‹Π²Π°Π΅Ρ‚ ΠΌΠ΅Ρ‚ΠΎΠ΄ __clone() ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°, Ссли это Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ).

$copy_of_object = clone $object;

ΠŸΡ€ΠΈ ΠΊΠ»ΠΎΠ½ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠΈ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°, PHP выполняСт ΠΏΠΎΠ²Π΅Ρ€Ρ…Π½ΠΎΡΡ‚Π½ΡƒΡŽ копию всСх свойств ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°. Π›ΡŽΠ±Ρ‹Π΅ свойства, ΡΠ²Π»ΡΡŽΡ‰ΠΈΠ΅ΡΡ ссылками Π½Π° Π΄Ρ€ΡƒΠ³ΠΈΠ΅ ΠΏΠ΅Ρ€Π΅ΠΌΠ΅Π½Π½Ρ‹Π΅, останутся ссылками.

function __clone(): void

ПослС Π·Π°Π²Π΅Ρ€ΡˆΠ΅Π½ΠΈΡ клонирования, Ссли ΠΌΠ΅Ρ‚ΠΎΠ΄ __clone() ΠΎΠΏΡ€Π΅Π΄Π΅Π»Ρ‘Π½, Ρ‚ΠΎ Π±ΡƒΠ΄Π΅Ρ‚ Π²Ρ‹Π·Π²Π°Π½ ΠΌΠ΅Ρ‚ΠΎΠ΄ __clone() вновь созданного ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π° для Π²ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎΠ³ΠΎ измСнСния всСх Π½Π΅ΠΎΠ±Ρ…ΠΎΠ΄ΠΈΠΌΡ‹Ρ… свойств.

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #1 ΠšΠ»ΠΎΠ½ΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°

<?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
$object1;
public
$object2;

function
__clone()
{
// ΠŸΡ€ΠΈΠ½ΡƒΠ΄ΠΈΡ‚Π΅Π»ΡŒΠ½ΠΎ ΠΊΠ»ΠΎΠ½ΠΈΡ€ΡƒΠ΅ΠΌ this->object1, ΠΈΠ½Π°Ρ‡Π΅
// ΠΎΠ½ Π±ΡƒΠ΄Π΅Ρ‚ ΡƒΠΊΠ°Π·Ρ‹Π²Π°Ρ‚ΡŒ Π½Π° ΠΎΠ΄ΠΈΠ½ ΠΈ Ρ‚ΠΎΡ‚ ΠΆΠ΅ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚.
$this->object1 = clone $this->object1;
}
}

$obj = new MyCloneable();

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

$obj2 = clone $obj;


print
"ΠžΡ€ΠΈΠ³ΠΈΠ½Π°Π»ΡŒΠ½Ρ‹ΠΉ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚:\n";
print_r($obj);

print
"ΠšΠ»ΠΎΠ½ΠΈΡ€ΠΎΠ²Π°Π½Π½Ρ‹ΠΉ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚:\n";
print_r($obj2);

?>

Π Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚ выполнСния ΠΏΡ€ΠΈΠ²Π΅Π΄Ρ‘Π½Π½ΠΎΠ³ΠΎ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π°:

ΠžΡ€ΠΈΠ³ΠΈΠ½Π°Π»ΡŒΠ½Ρ‹ΠΉ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 1
        )

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

)
ΠšΠ»ΠΎΠ½ΠΈΡ€ΠΎΠ²Π°Π½Π½Ρ‹ΠΉ ΠΎΠ±ΡŠΠ΅ΠΊΡ‚:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instance] => 3
        )

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

)

Π’ΠΎΠ·ΠΌΠΎΠΆΠ½ΠΎ ΠΎΠ±Ρ€Π°Ρ‰Π°Ρ‚ΡŒΡΡ ΠΊ свойствам/ΠΌΠ΅Ρ‚ΠΎΠ΄Π°ΠΌ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Ρ‡Ρ‚ΠΎ склонированного ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Π°:

ΠŸΡ€ΠΈΠΌΠ΅Ρ€ #2 Доступ ΠΊ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Ρ‡Ρ‚ΠΎ склонированному ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Ρƒ

<?php
$dateTime
= new DateTime();
echo (clone
$dateTime)->format('Y');
?>

Π’Ρ‹Π²ΠΎΠ΄ ΠΏΡ€ΠΈΠ²Π΅Π΄Ρ‘Π½Π½ΠΎΠ³ΠΎ ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° Π±ΡƒΠ΄Π΅Ρ‚ ΠΏΠΎΡ…ΠΎΠΆ Π½Π°:

2016
οΌ‹Π”ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ

ΠŸΡ€ΠΈΠΌΠ΅Ρ‡Π°Π½ΠΈΡ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ 11 notes

up
76
jorge dot villalobos at gmail dot com ΒΆ
21 years ago
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.
up
47
jojor at gmx dot net ΒΆ
16 years ago
Here is test script i wrote to test the behaviour of clone when i have arrays with primitive values in my class - as an additonal test of the note below by jeffrey at whinger dot nl

<pre>
<?php

class MyClass {

    private $myArray = array();
    function pushSomethingToArray($var) {
        array_push($this->myArray, $var);
    }
    function getArray() {
        return $this->myArray;
    }

}

//push some values to the myArray of Mainclass
$myObj = new MyClass();
$myObj->pushSomethingToArray('blue');
$myObj->pushSomethingToArray('orange');
$myObjClone = clone $myObj;
$myObj->pushSomethingToArray('pink');

//testing
print_r($myObj->getArray());     //Array([0] => blue,[1] => orange,[2] => pink)
print_r($myObjClone->getArray());//Array([0] => blue,[1] => orange)
//so array  cloned 

?>
</pre>
up
27
MakariVerslund at gmail dot com ΒΆ
19 years ago
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.
up
15
emile at webflow dot nl ΒΆ
16 years ago
Another gotcha I encountered: like __construct and __desctruct, you must call parent::__clone() yourself from inside a child's __clone() function. The manual kind of got me on the wrong foot here: "An object's __clone() method cannot be called directly."
up
12
ben at last dot fm ΒΆ
17 years ago
Here are some cloning and reference gotchas we came up against at Last.fm.

1. PHP treats variables as either 'values types' or 'reference types', where the difference is supposed to be transparent. Object cloning is one of the few times when it can make a big difference. I know of no programmatic way to tell if a variable is intrinsically a value or reference type. There IS however a non-programmatic ways to tell if an object property is value or reference type:

<?php

class A { var $p; }

$a = new A;
$a->p = 'Hello'; // $a->p is a value type
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  string(5) "Hello" // <-- no &
}
*/

$ref =& $a->p; // note that this CONVERTS $a->p into a reference type!!
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  &string(5) "Hello" // <-- note the &, this indicates it's a reference.
}
*/

?>

2. unsetting all-but-one of the references will convert the remaining reference back into a value. Continuing from the previous example:

<?php

unset($ref);
var_dump($a);

/*
object(A)#1 (1) {
  ["p"]=>
  string(5) "Hello"
}
*/

?>

I interpret this as the reference-count jumping from 2 straight to 0. However...

2. It IS possible to create a reference with a reference count of 1 - i.e. to convert an property from value type to reference type, without any extra references. All you have to do is declare that it refers to itself. This is HIGHLY idiosyncratic, but nevertheless it works. This leads to the observation that although the manual states that 'Any properties that are references to other variables, will remain references,' this is not strictly true. Any variables that are references, even to *themselves* (not necessarily to other variables), will be copied by reference rather than by value. 

Here's an example to demonstrate:

<?php

class ByVal
{
    var $prop;
}

class ByRef
{
    var $prop;
    function __construct() { $this->prop =& $this->prop; }
}

$a = new ByVal;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop remains at 1

$a = new ByRef;
$a->prop = 1;
$b = clone $a;
$b->prop = 2; // $a->prop is now 2

?>
up
4
stanislav dot eckert at vizson dot de ΒΆ
11 years ago
This base class automatically clones attributes of type object or array values of type object recursively. Just inherit your own classes from this base class.

<?php
    class clone_base
    {
        public function __clone()
        {
            $object_vars = get_object_vars($this);

            foreach ($object_vars as $attr_name => $attr_value)
            {
                if (is_object($this->$attr_name))
                {
                    $this->$attr_name = clone $this->$attr_name;
                }
                else if (is_array($this->$attr_name))
                {
                    // Note: This copies only one dimension arrays
                    foreach ($this->$attr_name as &$attr_array_value)
                    {
                        if (is_object($attr_array_value))
                        {
                            $attr_array_value = clone $attr_array_value;
                        }
                        unset($attr_array_value);
                    }
                }
            }
        }
    }
?>

Example:
<?php
    class foo extends clone_base
    {
        public $attr = "Hello";
        public $b = null;
        public $attr2 = array();

        public function __construct()
        {
            $this->b = new bar("World");
            $this->attr2[] = new bar("What's");
            $this->attr2[] = new bar("up?");
        }
    }

    class bar extends clone_base
    {
        public $attr;

        public function __construct($attr_value)
        {
            $this->attr = $attr_value;
        }
    }

    echo "<pre>";

    $f1 = new foo();
    $f2 = clone $f1;
    $f2->attr = "James";
    $f2->b->attr = "Bond";
    $f2->attr2[0]->attr = "Agent";
    $f2->attr2[1]->attr = "007";

    echo "f1.attr = " . $f1->attr . "\n";
    echo "f1.b.attr = " . $f1->b->attr . "\n";
    echo "f1.attr2[0] = " . $f1->attr2[0]->attr . "\n";
    echo "f1.attr2[1] = " . $f1->attr2[1]->attr . "\n";
    echo "\n";
    echo "f2.attr = " . $f2->attr . "\n";
    echo "f2.b.attr = " . $f2->b->attr . "\n";
    echo "f2.attr2[0] = " . $f2->attr2[0]->attr . "\n";
    echo "f2.attr2[1] = " . $f2->attr2[1]->attr . "\n";
?>
up
2
tolgakaragol at gmail dot com ΒΆ
6 years ago
Here is a basic example about clone issue. If we use clone in getClassB method. Return value will be same as new B() result. But it we dont use clone we can effect B::$varA. 

class A 
{
    protected $classB;
    
    public function __construct(){
        $this->classB = new B();
    }
    
    public function getClassB()
    {
        return clone $this->classB;
    }
}

class B
{
    protected $varA = 2;
    
    public function getVarA()
    {
        return $this->varA;
    }
    
    public function setVarA()
    {
        $this->varA = 3;
    }
}

$a = new A();

$classB = $a->getClassB();

$classB->setVarA();

echo $a->getClassB()->getVarA() . PHP_EOL;// with clone -> 2, without clone it returns -> 3

echo $classB->getVarA() . PHP_EOL; // returns always 3
up
5
Hayley Watson ΒΆ
18 years ago
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);
up
0
harl at gmail dot com ΒΆ
1 month ago
PHP 8.5 introduces a new clone() syntax that streamlines the common situation of wanting a clone but with some of the properties changed.

Writing $copy = clone($obj, ['field'] => $value) will make $copy a clone of $obj except that $copy->field will equal $value instead of whatever $obj->field was.

<?php

class Thingy
{
    public int $a;
    public int $b;
    // ..... etc. etc.
}

$foo = new Thingy;
$foo->a = 17;
$foo->b = 42;
// ... etc. etc.

$bar = clone($foo, ['a' => 0]);

echo "{$foo->a} {$foo->b} ...\n";
echo "{$bar->a} {$bar->b} ...\n";
?>
up
-4
fabio at naoimporta dot com ΒΆ
10 years ago
It's possible to know how many clones have been created of a  object. I'm think that is correct:

<?php

class Classe {

    public static $howManyClones = 0;

    public function __clone() {
        ++static::$howManyClones;
    }

    public static function howManyClones() {
        return static::$howManyClones;
    }

    public function __destruct() {
        --static::$howManyClones;
    }
}

$a = new Classe;

$b = clone $a;
$c = clone $b;
$d = clone $c;

echo 'Clones:' . Classe::howManyClones() . PHP_EOL;

unset($d);

echo 'Clones:' . Classe::howManyClones() . PHP_EOL;
up
-5
yinzw at chuchujie dot com ΒΆ
9 years ago
It's clearly depicted in the manual, about the mechanism of clone process:
- First, shallow copy: properties of references will keep references (refer to the same target/variable)
- Then, change content/property as requested (calling __clone method which is defined by user).

To illustrate this process, the following example codes seems better, comparing the the original version:

class SubObject
{
    static $num_cons = 0;
    static $num_clone = 0;

    public $construct_value;
    public $clone_value;

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

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

class MyCloneable
{
    public $object1;
    public $object2;

    function __clone()
    {
        // εΌΊεˆΆε€εˆΆδΈ€δ»½this->object, ε¦εˆ™δ»η„ΆζŒ‡ε‘εŒδΈ€δΈͺ对豑
        $this->object1 = clone $this->object1;
    }
}

$obj = new MyCloneable();

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

$obj2 = clone $obj;

print("Original Object:\n");
print_r($obj);
echo '<br>';
print("Cloned Object:\n");
print_r($obj2);

==================

the output is as below

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [construct_value] => 1
            [clone_value] => 
        )

    [object2] => SubObject Object
        (
            [construct_value] => 2
            [clone_value] => 
        )

)
<br>Cloned Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [construct_value] => 1
            [clone_value] => 1
        )

    [object2] => SubObject Object
        (
            [construct_value] => 2
            [clone_value] => 
        )

)