php基础之引用传值


php中赋值有COW机制Copy On Wirte,引用传值&后没有COW机制

demo1.php

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/1/5
* Time: 8:40
*/
$a=range(0,1000);
var_dump(memory_get_usage());
$b=&$a;
var_dump(memory_get_usage());
$a=range(0,1000);
var_dump(memory_get_usage());

demo2.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/1/5
* Time: 8:43
*/
$a=range(1,5);
xdebug_debug_zval('a');
$b=&$a;
xdebug_debug_zval('b');
$a=range(1,5);
xdebug_debug_zval('a');

unset取消引用不会销毁
对象本身就是引用传值,对象本身不会复制,用clone()复制
demo3.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/1/5
* Time: 9:26
*/
class Person{
public $name="zhangsan";
}
$p1=new Person();
xdebug_debug_zval('p1');
$p2=$p1;
xdebug_debug_zval('p1');
$p1->name="lisi";
xdebug_debug_zval('p1');

结果如下

1
2
3
4

p1: (refcount=1, is_ref=0)=class Person { public $name = (refcount=2, is_ref=0)='zhangsan' }
p1: (refcount=2, is_ref=0)=class Person { public $name = (refcount=2, is_ref=0)='zhangsan' }
p1: (refcount=2, is_ref=0)=class Person { public $name = (refcount=1, is_ref=0)='lisi' }

文章作者: Jacky
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Jacky !
  目录