PHP从变量中删除“引用”。

17

我有下面的代码。我想改变 $b 的值,以便可以再次使用它的值。但是如果这么做,$a 也会被更改。在之前将 $b 分配为 $a 的引用后,如何重新为 $b 分配一个值?

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

// later
$b = null;
4个回答

18

请参见内联说明

$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 a new life.

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

unset($b);
// later
$b = null;

这个答案缺少教育性的解释。 - mickmackusa

5
@xdazz的答案是正确的,但请看PHP手册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

3
首先,将$a指向$b会在这两个变量之间建立连接(用缺乏更好词汇来形容),因此当$b发生变化时,$a也随之改变,这正是该操作的预期效果。
因此,如果您想要断开引用,最简单的方法是:
unset($b);
$b="new value";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接