从类中访问全局变量 [英] Access global variable from within a class

查看:53
本文介绍了从类中访问全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(简化的)代码:

I have the following (stripped down) code:

<?PHP
    class A {
        function Show(){
            echo "ciao";
        }
    }

    $a = new A();
    $b = new B();

    class B {
        function __construct() {
            $a->Show();
        }
    }
?>

有点意外,我无法从类内部访问全局定义的$ a变量,并且出现了 Undefined variable 异常.有帮助吗?

With a bit of surprise I cannot access the globally defined $a variable from within the class and I get a Undefined variable exception. Any help?

推荐答案

为什么会感到惊讶?那是一个相当合理的变量范围问题...

Why the surprise? That's a pretty logical variable scope problem there...

我建议您使用global关键字或变量$GLOBALS来访问变量.

I suggest you use either the global keyword or the variable $GLOBALS to access your variable.

编辑:因此,在您的情况下,将是:

So, in your case that will be:

global $a;
$a->Show();

$GLOBALS['a']->Show();

而且,由于Vinko是正确的,我建议您阅读有关

EDIT 2: And, since Vinko is right, I suggest you take a look at PHP's manual about variable scope.

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

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