PHP $ GLOBALS ['variable']之间有什么区别; 和全球$变量;

ale*_*ale 3 php scope global-variables

请看以下两个例子:

例1:

$variable = 'some value';

class Foo {
   public function bar() {
      global $variable;
      print $variable;       
   }
}
Run Code Online (Sandbox Code Playgroud)

例2:

$variable = 'some value';

class Foo {
   public function bar() {
      print $GLOBALS['variable'];  
   }    
}
Run Code Online (Sandbox Code Playgroud)

示例可以像这样使用:

$foo = new Foo();
$foo->bar();
Run Code Online (Sandbox Code Playgroud)

两者似乎做同样的事情?有什么不同?有一种方式比另一种更好吗?为什么有两种不同的方法呢?

第一个例子对我来说似乎很奇怪,因为它看起来像一个声明,然后使用变量而不指定它.看起来很奇怪.

谢谢.

Del*_*ani 6

global关键字"进口"的变量到本地范围,同时通过访问全球$GLOBALS没有.