php版本 7.2
$empty = [];
xdebug_debug_zval('empty');
输出:
empty: (refcount=2, is_ref=0)=array ()
这牵扯到 PHP7 中的另一个概念,叫做 immutable array (不可变数组),在不可变数组下,使用一个伪计数值2。类型是这种直接申明规定数组
array(1,2,3)的refcount = 2 你可以看下 array("time"=>time())这样的申明,就是1。
摘抄一段PHP7数组开发成员的一段原话,你可以看看。
For arrays the not-refcounted variant is called an "immutable array". If you use opcache, then constant array literals in your code will be converted into immutable arrays. Once again, these live in shared memory and as such must not use refcounting. Immutable arrays have a dummy refcount of 2, as it allows us to optimize certain separation paths.
一. 为什么某些变量的引用计数器的初始值为 0
$var_int = 233;
$var_float = 233.3;
$var_str = '233';
xdebug_debug_zval('var_int');
xdebug_debug_zval('var_float');
xdebug_debug_zval('var_str');
/** 输出 **
var_int: (refcount=0, is_ref=0)=233
var_float: (refcount=0, is_ref=0)=233.3
var_str: (refcount=1, is_ref=0)='233'
**********/
原因
在 PHP7 中,为一个变量赋值的时候,包含了两部分操作:
- 为符号量(即变量名)申请一个 zval_struct结构
- 将变量的值储存到 zval_struct.value中 对于 zval 在 value 字段中能保存下的值,就不会在对他们进行引用计数, 而是在拷贝的时候直接赋值 ,这部分类型有:
- IS_LONG
- IS_DOUBLE
即我们在 PHP 中的 整形 与 浮点型 。
对于xdebug_debug_zval('var_str'); 不同php版本输出有点差别:
PHP 7.2.24
var_str: (interned, is_ref=0)='233'
PHP 7.3.5
var_str: (refcount=1, is_ref=0)='233'