note 119554 added to language.oop5.cloning
| From: | yinzw at chuchujie dot com | Date: | Tue, 05 Jul 2016 13:10:45 +0000 |
| Subject: | note 119554 added to language.oop5.cloning | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-205890@lists.php.net to get a copy of this message | ||
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] =>
)
)
----
Server IP: 72.52.91.14
Probable Submitter: 118.194.197.58
----
Manual Page -- http://php.net/manual/en/language.oop5.cloning.php
Edit -- https://master.php.net/note/edit/119554
Del: integrated -- https://master.php.net/note/delete/119554/integrated
Del: useless -- https://master.php.net/note/delete/119554/useless
Del: bad code -- https://master.php.net/note/delete/119554/bad+code
Del: spam -- https://master.php.net/note/delete/119554/spam
Del: non-english -- https://master.php.net/note/delete/119554/non-english
Del: in docs -- https://master.php.net/note/delete/119554/in+docs
Del: other reasons-- https://master.php.net/note/delete/119554
Reject -- https://master.php.net/note/reject/119554
Search -- https://master.php.net/manage/user-notes.php