在PHP函数中访问全局变量

在PHP函数中访问全局变量

问题描述:

根据大多数编程语言的作用域规则,我可以访问在函数内部定义的变量,但是为什么此代码不起作用?

According to the most programming languages scope rules, I can access variables that are defined outside of functions inside them, but why doesn't this code work?

<?php
    $data = 'My data';

    function menugen() {
        echo "[" . $data . "]";
    }

    menugen();
?>

输出为[].

它不起作用,因为您必须声明要访问的全局变量:

It is not working because you have to declare which global variables you'll be accessing:

$data = 'My data';

function menugen() {
    global $data; // <-- Add this line

    echo "[" . $data . "]";
}

menugen();

否则,您可以作为$GLOBALS['data']来访问它.参见 变量范围 .

Otherwise you can access it as $GLOBALS['data']. See Variable scope.

即使有些偏离主题,我还是建议您完全避免使用全局变量,而更希望将其作为参数传递.

Even if a little off-topic, I'd suggest you avoid using globals at all and prefer passing as parameters.