dousou2911 2019-06-08 04:21
浏览 78

为什么这个PHP代码输出正确?

Yo, I'm studying and relearning some old PHP basics and I got to superglobals

I don't quite understand why this PHP code is as well as why the superglobal doesn't add to be 15 when logically 10 isn't 15, and help or pointers so I can understand this?

$y = 10;
$x = 5;

$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];

I've tried researching this on my own and accepting its because y is just the name of the super global index

none to show other than what's in the question

<?php 
$x = 5; 
$y = 10; 

function myTest() { 
    $GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y']; 
} 
myTest(); 
echo $y; // outputs 15 
?>

the only error here is my brain

When I look at the code I see $GLOBAL['10'] = $GLOBAL['5'] + $GLOBALS['10'];

I don't understand how 15 can equal 10.

  • 写回答

1条回答 默认 最新

  • dongxianghui3709 2019-06-08 04:42
    关注

    When you refer to a variable outside a function it refers to the global variable. When you refer to a variable inside a function, it normally refers to the local variable, unless the function contains a global declaration that makes that variable global.

    You can also use the super-global $GLOBALS, which always refers to the global variables named in its keys. The documentation describes it as:

    An associative array containing references to all variables which are currently defined in the global scope of the script. The variable names are the keys of the array.

    So when you use $GLOBALS['y'] it's the same as using the global variable $y. Your function is equivalen to:

    function myTest() { 
        global $x, $y;
        $y = $x + $y;
    } 
    
    评论

报告相同问题?

悬赏问题

  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多