php - 在php中取消设置变量

标签 php static unset

我刚刚通过 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 被删除。

参见 reference count basics .

关于php - 在php中取消设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3189814/

相关文章:

python - 静态类成员python

php - 何时在 PHP 中使用静态修饰符

php - 在迭代数组时使用 unset() 来删除空值

php - 在特定条件后如何显示表格?

Java - 为什么 ClassName.this.variable 在变量为静态时起作用?

php - SQL查询的 Eloquent 表示

cmake - 如何手动将 CMake 路径变量设置为 NOTFOUND?

php - 删除 cookie 时出现问题,不会取消设置

php - 使 .htaccess 使用前端 Controller 重写对/web 的所有请求?

php - 测试驱动开发和接口(interface)