我有下面的代码。我想改变 $b 的值,以便可以再次使用它的值。但是如果这么做,$a 也会被更改。在之前将 $b 分配为 $a 的引用后,如何重新为 $b 分配一个值?
$a = 1;
$b = &$a;
// later
$b = null;
请参见内联说明
$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.
$a = 1;
$b = &$a;
unset($b);
// later
$b = null;
$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
$a
指向$b
会在这两个变量之间建立连接(用缺乏更好词汇来形容),因此当$b
发生变化时,$a
也随之改变,这正是该操作的预期效果。unset($b);
$b="new value";