【问题标题】:PHP remove "reference" from a variable.PHP 从变量中删除“引用”。
【发布时间】:2012-01-27 09:13:33
【问题描述】:

我有下面的代码。我想更改 $b 以再次将其与值一起使用。如果我这样做,它也会改变 $a 。在之前将值分配为 $a 的引用后,如何再次为 $b 分配值?

$a = 1;
$b = &$a;

// later
$b = null;

【问题讨论】:

    标签: php variables reference


    【解决方案1】:

    查看内联解释

    $a = 1;    // Initialize it
    $b = &$a;  // Now $b and $a becomes same variable with just 2 different names  
    unset($b); // $b name is gone, vanished from the context  But $a is still available  
    $b = 2;    // Now $b is just like a new variable with a new value. Starting new life.
    

    【讨论】:

      【解决方案2】:
      $a = 1;
      $b = &$a;
      
      unset($b);
      // later
      $b = null;
      

      【讨论】:

      • 这个答案缺少教育解释。
      【解决方案3】:

      @xdazz 的回答是正确的,但只是从PHP Manual 添加以下很好的示例,它可以深入了解 PHP 在幕后所做的事情。

      在此示例中,您可以看到函数 foo() 中的 $bar 是对函数范围变量的静态引用。

      取消设置 $bar 会删除引用但不会释放内存:

      <?php
      function foo()
      {
          static $bar;
          $bar++;
          echo "Before unset: $bar, ";
          unset($bar);
          $bar = 23;
          echo "after unset: $bar\n";
      }
      
      foo();
      foo();
      foo();
      ?>
      

      上面的例子会输出:

      Before unset: 1, after unset: 23
      Before unset: 2, after unset: 23
      Before unset: 3, after unset: 23
      

      【讨论】:

        【解决方案4】:

        首先:创建从$a$b 的引用会在两个变量之间创建连接(因为没有更好的词),所以$a$b 更改时更改正是它的方式是为了工作。

        所以,假设你想打破引用,最简单的方法就是

        unset($b);
        $b="new value";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-08-04
          • 2022-07-03
          • 1970-01-01
          • 2017-10-19
          • 2010-12-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多