PHP: Globals, SuperGlobals -如何使一个变量的值对所有函数都可访问


PHP: Globals, SuperGlobals - How to make a variable's value accessible to all functions?

我有一个PHP程序,我正在编写大约200行代码。它有很多我写的函数,可能有十几个。我想在程序中有一个调试选项,但希望该值可以在所有函数中访问。如何以及在哪里定义?

Global $debug_status;
function blah ($message) {
if ($debug_status == "1" ) {
  do something...}
...
}

这是正确的方法吗?谢谢!

使用常量

define('DEBUG', true);

if (DEBUG) ...

当然有更好的调试方法。例如,使用OOP,将记录器实例注入到每个对象中,调用

$this->logger->debug(...);

记录消息,切换记录器的输出过滤器以显示或隐藏调试消息。

你就快到了....global关键字将对全局变量的引用导入当前作用域。

$debug_status = "ERROR";
function blah ($message) {
    global $debug_status;
    if ($debug_status == "1" ) {
      do something...}
      ...
    }

变量应该在Registry类中定义,这是一种模式。

演示工作

注册表示例

class Registry {
   private static $registry = array();
   private function __construct() {} //the object can be created only within a class.
   public static function set($key, $value) { // method to set variables/objects to registry
      self::$registry[$key] = $value;
   }
   public static function get($key) { //method to get variable if it exists from registry
      return isset(self::$registry[$key]) ? self::$registry[$key] : null;
   }
}
使用

注册对象需要包含这个类

$registry::set('debug_status', $debug_status); //this line sets object in **registry**

获取对象可以使用get方法

$debug_status = $registry::get('debug_status'); //this line gets the object from **registry**

这是每个对象/变量都可以存储的解决方案。对于你写的这样的目的,最好使用简单的常数和define()

我的解决方案适用于应用程序中应该从任何地方访问的任何类型的对象。

编辑

删除singleton和make get、set方法,使它们像@ decize建议的那样是静态的