php中clone和new的区别
2个回答
展开全部
比如现在有一个类 class Person{ function demo (){ return "ok!"; } } $one = new Person(); $two = new Person(); ---------------------------- $one = new Person(); $two = clone $one;
第一种是$one和$two没有关系,第二种两者只是名字不同,一个改变另一个也会改变
1 <?php
2 class Account {
3 public $balance;
4
5 public function __construct($balance) {
6 $this->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);
推荐于2016-08-29
展开全部
1 <?php
2 class Account {
3 public $balance;
4
5 public function __construct($balance) {
6 $this->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
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询