您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PHP中的__clone()

2024/7/14 7:41:47发布22次查看
php的__clone()方法对一个对象实例进行的浅复制,对象内的基本数值类型进行的是传值复制,而对象内的对象型成员变量,如果不重写__clone方法,显式的clone这个对象成员变量的话,这个成员变量就是传引用复制,而不是生成一个新的对象.如第28行注释所说
1 balance = $balance; 7 } 8 } 9 10 class person {11 private $id;12 private $name;13 private $age;14 public $account;15 16 public function __construct($name, $age, account $account) {17 $this->name = $name;18 $this->age = $age;19 $this->account = $account;20 }21 22 public function setid($id) {23 $this->id = $id;24 }25 26 public function __clone() { #复制方法,可在里面定义再clone是进行的操作27 $this->id = 0;28 $this->account = clone $this->account; #不加这一句,account在clone是会只被复制引用,其中一个account的balance被修改另一个也同样会被修改29 }30 }31 32 $person = new person(peter, 15, new account(1000));33 $person->setid(1);34 $person2 = clone $person;35 36 $person2->account->balance = 250;37 38 var_dump($person, $person2);39 40 ?>
输出:
object(person)#1 (4) { [id:person:private]=> int(1) [name:person:private]=> string(5) peter [age:person:private]=> int(15) [account]=> object(account)#2 (1) { [balance]=> int(1000) } } object(person)#3 (4) { [id:person:private]=> int(0) [name:person:private]=> string(5) peter [age:person:private]=> int(15) [account]=> object(account)#4 (1) { [balance]=> int(250) } }
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product