企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 9.3 PHP中的资源类型 # 9.3 PHP中的资源类型 zval通过引用计数来节省内存的,这个我们都知道了,但你可能不知道的是,某个zval对应的{资源}在实现时也使用了引用计数这种概念,也就是有了两种引用计数! {资源}对应的zval的类型是IS\_RESOURCE,它并不保存最终的数据,而只保存一个数字,即EG(regular\_list)中的数字索引。 当{资源}被创建时,比如我们调用sample\_fopen()函数: ``` $a = sample_fopen('notes.txt', 'r'); //此时:var->refcount__gc = 1, rsrc->refcount = 1 $b = $a; //此时:var->refcount__gc = 2, rsrc->refcount = 1 unset($b); //此时:var->refcount__gc = 1, rsrc->refcount = 1 /* 下面来个复杂的! */ $b = $a; $c = &$a; //此时: /* bvar->refcount = 1, bvar->is_ref = 0 acvar->refcount = 2, acvar->is_ref = 1 rsrc->refcount = 2 */ ``` 现在,如果我们unset($b),内核只会把rsrc->refcount的值减1。只有当rsrc->refcount的值为0时,我们预设的dtor释放函数才会被激活并调用。 ## links - 9.2 [Persistent Resources](9.2.html) - 9.4 [第九章小结](9.4.html)