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

demo1.php

<?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

<?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

<?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');

结果如下


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' }

本文由 admin 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论