当你打电话时,你只记得这一点:
<?php
$a = 1 ;
echo "As initial, the real 'a' is..".$a."<br/>";
$b = &$a ; // it's meaning $b has the same value as $a, $b = $a AND SO $a = $b (must be)
$b += 5;
echo "b is equal to: ".$b." and a equal to: ".$a."<br/>";
echo " Now we back as initial, when a=1... (see the source code) <br/>";
$a = 1 ;
echo "After we back : b is equal to: ".$b." and a equal to: ".$a."<br/>";
echo "Wait, why b must follow a? ... <br/> ..what about if we change b alone? (see the source code)<br/>";
$b = 23;
echo "After we change b alone, b equal to: ".$b." and a equal to: ".$a."<br/>";
echo " WHAT ?? a ALSO CHANGED ?? a and b STICK TOGETHER?!! </br>" ;
echo "to 'clear this, we use 'unset' function on a (see the source code)<br/> ";
unset($a);
$b = 66;
$a = 1;
echo "Now, after unset,b is equal to: ".$b." and a equal to: ".$a."<br/>";
?>
输出将是:
As initial, the real 'a' is..1
After the Reference operator...(see the source code)
b is equal to: 11 and a equal to: 11
Now we back as initial... (see the source code)
After we back : b is equal to: 1 and a equal to: 1
Wait, why b must follow a? ...
..what about if we change b alone? (see the source code)
After we change b alone, b equal to: 23 and a equal to: 23
WHAT ?? a ALSO CHANGED ?? a and b STICK TOGETHER?!!
to 'clear this, we use 'unset' function on a (see the source code)
Now, after unset,b is equal to: 66 and a equal to: 1
审查:
为什么发生了$a
变化?那是因为&
(与号运算符)&
作为参考变量,因此它存储在“临时内存”中。当您初始化时$b= &$a
,请参阅我的评论$b = $a
, $a = $b
这意味着每当您修改时$b
,$a
也被修改,反之亦然。他们被锁链了!这就是引用运算符的简单含义。
刚开始可能会觉得很困惑,但是一旦你成为这方面的专家,你就可以处理这个操作符来做一个这样的“切换”功能:
<?php
function bulbswitch(&$switch)
{
$switch = !$switch;
}
function lightbulb($a)
{
if ($a == true) { echo 'a is On <br/>';}
else { echo 'a is Off <br/>';}
}
$a = true ;
echo 'At the begining, a is On, then.... <br/>';
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
?>
输出将是:
At the begining, a is On, then....
a is Off
a is On
a is Off
a is On
a is Off
a is On