php 从类中访问全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1877136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access global variable from within a class
提问by pistacchio
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 variableexception. Any help?
有点惊讶的是,我无法从类中访问全局定义的 $a 变量,并且出现了未定义的变量异常。有什么帮助吗?
采纳答案by Franz
Why the surprise? That's a pretty logical variable scope problem there...
为什么会有惊喜?这是一个非常合乎逻辑的变量范围问题......
I suggest you use either the globalkeyword or the variable $GLOBALSto 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 的有关变量范围的手册。
回答by Galen
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();
}
}
回答by LiraNuna
You will need to define it as a globalvariableinside the scope of the function you want to use it at.
您需要将其定义为要使用它的函数范围内的global变量。
function __construct() {
global $a;
$a->Show();
}
回答by Jay Zeng
<?php
class A {
public function Show(){
return "ciao";
}
}
class B {
function __construct() {
$a = new A();
echo $a->Show();
}
}
$b = new B();
?>

