Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: six minus five?
(Example: nine)

The Note You're Voting On

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] =>
)

)

<< Back to user notes page

To Top