<?php
class Temp{
public $tempValue;
function __construct($tempValue){
$this->tempValue = $tempValue;
}
}
class Person{
public $name;
public $age;
public $sex;
public $myTemp;
function __construct($name,$age,$sex,Temp $myTemp){
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
$this->myTemp = $myTemp;
}
function say(){
}
function __tostring(){
return "__toString() is used.<br>";
}
function __clone(){
echo "__clone() is used.<br>";
$this->myTemp = clone $this->myTemp;//若没有这一句,则$q->myTemp->tempValue=50;时,浅复制,并未给q的myTemp在内存中分配空间,只是指向了p的myTemp,所以p的myTemp也会随之改变。
}
}
$tempP = new Temp(100);
$p = new Person('aa',10,'man',$tempP);
$r = $p;
$r->name = 'cc';
var_dump($p);
var_dump($r);
echo "<hr/>";
$q = clone $p;//此时自动调用__clone()
$q->name = 'bb';
var_dump($p);
var_dump($q);
echo "<hr/>";
$q->myTemp->tempValue = 50;
var_dump($p);
var_dump($q);
自己通过网页输出看一下吧~