How to explain the two $this in the __clone() method of PHP? What do they mean?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
How to explain the two $this in the __clone() method of PHP? What do they mean?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
There are no two
$this in
__clone()
, only one $this
. This $this
points to the cloned new object, because the __clone()
method is called in the new object called.
When performing cloning, PHP will first perform a shallow copy, create a new object, and copy all the attributes of the original object to the new object. For reference variables such as objects and resources, only their pointers are copied, but they are not cloned. If you need to make a deep copy of these properties, you need to clone them separately in __clone()
.
For example:
1 2 3 4 5 6 7 8 9 |
|
Note here that the two $this->obj
both refer to the $obj
attribute of the new class, because when cloning, the $obj
of the new object has been shallowly copied from the original object. This is just because We want to make a deep copy, so we clone $this->obj
again.