dongxian8858 2014-07-01 23:23
浏览 24

php中的全局引用

I read this article on php.net:

"When you declare a variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:

<?php
$var =& $GLOBALS["var"];
?>

This also means that unsetting $var won't unset the global variable."

What I understand from this is that when you declare a variable as global $var, you set another name for the variable name $GLOBALS["var"]. So if you echo one or another, you get the same thing. But I find the last sentence confusing, since the following snippet outputs 'red':

$GLOBALS['var']='blue';
global $var;  //This is supposed to be equivalent to $var=& $GLOBALS["var"];
//echo $var,'<br/>';
$var='red';
echo $GLOBALS['var']; //I would expect this to output 'blue', instead of 'red'

I was expecting the output to be 'blue' since it states that unsetting $var won't unset the global variable. Where're the mistake?

If I do unset($var), how should I check that the global variable was not unset?

  • 写回答

2条回答 默认 最新

  • douzhong6480 2014-07-01 23:30
    关注

    You need to understand that you missed that minor detail, the &. What that does, is it says you want the original reference and not a copy of the variable.

    function test() {
        $var = $GLOBALS['x'];
        $var2 = &$GLOBALS['x'];
        echo $GLOBALS['x'] . "
    ";
        $var2 = 'red';
        echo $var . "
    " . $GLOBALS['x'];
    
    }
    
    $x = 'blue';
    test();
    

    This outputs

    blue
    red
    

    You'll note that $var was assigned to global version, but what happened was PHP only copied $x. With $var2, we told PHP that we wanted the reference, or, in other words, the actual address of $x. This makes a huge difference because $var is only a copy. Changing it only changes the copy. Note in my example that I changed the value of $x, but only $var2 reflected that change. $var still had what $x was at the beginning.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!