求解php的__clone()方法中的两个$this怎么解释?分别是什么含义?
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 | <code> class Person
{
var $sex ;
var $age ;
function __construct( $name , $sex , $age ) {
$this ->name = $name ;
$this ->sex = $sex ;
$this ->age = $age ;
}
function say() {
echo "我的名字叫:" . $this ->name . " 性别:" . $this ->sex . " 我的年龄是:" . $this
->age . "<br>" ;
}
function __clone() {
$this ->name = "我是复制的张三$this->name" ;
}
}
$p1 = new Person ( "张三" , "男" , 20 );
$p2 = clone $p1 ;
$p1 ->say ();
$p2 ->say ();</code>
|
Copier après la connexion
Copier après la connexion
回复内容:
求解php的__clone()方法中的两个$this怎么解释?分别是什么含义?
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 | <code> class Person
{
var $sex ;
var $age ;
function __construct( $name , $sex , $age ) {
$this ->name = $name ;
$this ->sex = $sex ;
$this ->age = $age ;
}
function say() {
echo "我的名字叫:" . $this ->name . " 性别:" . $this ->sex . " 我的年龄是:" . $this
->age . "<br>" ;
}
function __clone() {
$this ->name = "我是复制的张三$this->name" ;
}
}
$p1 = new Person ( "张三" , "男" , 20 );
$p2 = clone $p1 ;
$p1 ->say ();
$p2 ->say ();</code>
|
Copier après la connexion
Copier après la connexion
__clone()
中没有两个$this
,只有一个$this
,这个$this
所指向的是克隆出来的新对象,因为__clone()
方法是在新对象中被调用的。
在执行克隆时,PHP会先进行一次浅复制,新建一个对象,将原对象中的属性全部复制到新对象中。对于对象、资源这类引用变量,只是复制它们的指针,而不会克隆它们。如果需要对这些属性进行深复制,则需要在__clone()
单独对其进行克隆。
例如:
1 2 3 4 5 6 7 8 9 | <code> class MyCloneable
{
public $obj ;
function __clone()
{
$this ->obj = clone $this ->obj;
}
}</code>
|
Copier après la connexion
这里注意,两个$this->obj
都指的是新类的$obj
属性,因为克隆的时候新对象的$obj
已经从原对象浅复制过来了,这里只是因为我们要进行深复制,所以对$this->obj
再执行了一次克隆。