我刚刚通过 php 手册阅读了有关未设置变量的信息。
php手册说 "unset() 销毁指定的变量"
在我遇到静态变量之前,这个 def 看起来很完美...... “如果静态变量在函数内部被 unset(),unset() 只会在函数其余部分的上下文中销毁该变量。后续调用将恢复变量的先前值。”
这个定义对我来说似乎不是一个好定义,至少,因为“销毁变量”意味着变量不再与该内存位置相关联。
有没有人认为更好的定义是“unset() 使变量超出当前范围”?我的意思是,与其指向生命周期,不如在这里使用词范围更好?
最佳答案
让我们考虑一下函数:
function foo() {
static $bar;
$bar++;
unset($bar);
}
foo(); //static $bar is 1
foo(); //static $bar is 2
函数编译为:
function name: foo number of ops: 11 compiled vars: !0 = $bar line # * op fetch ext return operands --------------------------------------------------------------------------------- 2 0 > EXT_NOP 4 1 EXT_STMT 2 FETCH_W static $0 'bar' 3 ASSIGN_REF !0, $0 5 4 EXT_STMT 5 POST_INC ~1 !0 6 FREE ~1 6 7 EXT_STMT 8 UNSET_VAR !0 7 9 EXT_STMT 10 > RETURN null
A variable actually exists outside each function call to foo()
and, on each call, it's fetched and a reference to it is assigned to $bar
. In fact, it's very similar to this:
function foo() {
global $bar;
$bar++;
unset($bar);
}
当您调用 unset()
时,您只是在销毁您创建的引用,而不是基础值。
我没有确认,但我猜是这样的:
- 存储变量(zval)的底层表示,以便其引用计数为 1。
- 当
foo()
被调用时,符号$bar
与这个 zval 相关联,它的引用计数增加到 2 并且引用标志被设置。< - 当
unset
被调用时,zval 的引用计数减少到 1,引用标志可能被清除并且符号$bar
被删除。
关于php - 在php中取消设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3189814/