首页 > 解决方案 > 如何在 PHP 5.6 版本中使用全局常量而不是类常量

问题描述

我正在使用Monolog创建我的应用程序的日志记录系统。在核心应用程序文件中,创建新的 Monolog 对象后,我需要在日志文件中选择要打印的日志级别。我想使用一个全局常量LOG_LEVEL,它可以是“DEBUG”、“INFO”等。我需要 Monolog 类将其值视为类常量。

// content of config.php
// Here I declare the constants in a separate file called 'config.php'
define("LOG_FILE", "patch/to/my/log.log");
define("LOG_LEVEL", "ERROR");

// content of app.php
require 'config.php';
require 'vendor/autoload.php';

$container['logger'] = function($c) {
    $logger = new \Monolog\Logger('logger');
    error_log('log level ' . LOG_LEVEL); // prints 'log level ERROR'

    $fileHandler = new \Monolog\Handler\StreamHandler(LOG_FILE, $logger::LOG_LEVEL); // here I get the error 'Undefined class constant LOG_LEVEL'
    //the normal syntax would be '$logger::ERROR' in this case and that works fine

    $logger->pushHandler($fileHandler);
    return $logger;
};

我需要'LOG_LEVEL'常量被独白类用作'ERROR',而不是'LOG_LEVEL'。我在这里做错了什么,现在已经搜索了几个小时没有任何运气的答案。

标签: phpconstantsmonologclass-constants

解决方案


您现在正在执行$logger::LOG_LEVEL'LOG_LEVEL' 从类中取出$logger(在本例中为 a \Monolog\Logger)。那没有名为 LOG_LEVEL 的静态变量,因此您得到未定义的变量。
您刚刚在任何类中定义了“LOG_LEVEL”,因此:

 $fileHandler = new \Monolog\Handler\StreamHandler(LOG_FILE, LOG_LEVEL); 

花哨的解决方案:

您可以做一个静态类并将其包含在您的主页中:

Class CONFIG {
    public static $LOG_LEVEL = 'default Value';
}

// Then you can use this anywhere:
CONFIG::$LOG_LEVEL
$fileHandler = new \Monolog\Handler\StreamHandler(LOG_FILE, CONFIG::$LOG_LEVEL); 

这样做的好处是只有一个配置文件,而不是分散在各种文件中,这很快就会变得非常烦人。


推荐阅读