从类中访问全局变量

时间:2022-05-06 03:37:33

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();
        }
    }
?>

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?

有点意外,我无法从类中访问全局定义的$ a变量,我得到一个Undefined变量异常。有帮助吗?

4 个解决方案

#1


5  

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

为何惊喜?这是一个非常合理的变量范围问题......

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

我建议你使用global关键字或变量$ GLOBALS来访问你的变量。

EDIT: So, in your case that will be:

编辑:那么,在你的情况下将是:

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

or

要么

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

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

编辑2:而且,既然Vinko是对的,我建议你看一下关于变量范围的PHP手册。

#2


18  

please don't use the global method that is being suggested. That makes my stomach hurt.

请不要使用建议的全局方法。这让我肚子疼。

Pass $a into the constructor of B.

将$ a传递给B的构造函数。

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

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

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

#3


6  

You will need to define it as a global variable inside the scope of the function you want to use it at.

您需要将其定义为要在其中使用的函数范围内的全局变量。

function __construct() {
    global $a;
    $a->Show();
}

#4


0  

<?php
class A {
    public function Show(){
      return "ciao";
    }
}

class B {
    function __construct() {
        $a = new A();
        echo $a->Show();
    }
}

$b = new B();
?>

#1


5  

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

为何惊喜?这是一个非常合理的变量范围问题......

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

我建议你使用global关键字或变量$ GLOBALS来访问你的变量。

EDIT: So, in your case that will be:

编辑:那么,在你的情况下将是:

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

or

要么

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

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

编辑2:而且,既然Vinko是对的,我建议你看一下关于变量范围的PHP手册。

#2


18  

please don't use the global method that is being suggested. That makes my stomach hurt.

请不要使用建议的全局方法。这让我肚子疼。

Pass $a into the constructor of B.

将$ a传递给B的构造函数。

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

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

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

#3


6  

You will need to define it as a global variable inside the scope of the function you want to use it at.

您需要将其定义为要在其中使用的函数范围内的全局变量。

function __construct() {
    global $a;
    $a->Show();
}

#4


0  

<?php
class A {
    public function Show(){
      return "ciao";
    }
}

class B {
    function __construct() {
        $a = new A();
        echo $a->Show();
    }
}

$b = new B();
?>