在PHP函数中访问全局变量 [英] Access a global variable in a PHP function

查看:110
本文介绍了在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.

这篇关于在PHP函数中访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆