PHP从变量中删除"引用".

dio*_*emo 12 php variables reference

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

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

// later
$b = null;
Run Code Online (Sandbox Code Playgroud)

Shi*_*dim 14

请参阅内联说明

$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.
Run Code Online (Sandbox Code Playgroud)


xda*_*azz 7

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

unset($b);
// later
$b = null;
Run Code Online (Sandbox Code Playgroud)


Pau*_*ain 5

@xdazz的答案是正确的,但只是在PHP手册中添加以下很好的例子,它可以深入了解PHP在幕后的工作.

在此示例中,您可以看到$bar函数foo()中是函数作用域变量的静态引用.

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

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

foo();
foo();
foo();
?>
Run Code Online (Sandbox Code Playgroud)

上面的例子将输出:

Before unset: 1, after unset: 23
Before unset: 2, after unset: 23
Before unset: 3, after unset: 23
Run Code Online (Sandbox Code Playgroud)