php - 如何在 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'。我在这里做错了什么,现在已经搜索了几个小时没有任何运气的答案。
解决方案
您现在正在执行$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);
这样做的好处是只有一个配置文件,而不是分散在各种文件中,这很快就会变得非常烦人。
推荐阅读
- dictionary - 如何在机器人框架中使用带有 2 个参数的 For 循环?
- flask - Python Flask 未与 docker-compose 一起运行
- python-3.x - 在OpenGL中绘制到半透明帧缓冲区时如何抗锯齿?
- python - 对不同类型使用相同的功能
- opencv - 使用 opencv 和 tesseract (java) 识别 carattere
- javascript - 具有自定义应用函数的节点 javascript 数组解构
- angular - Angular 11:NullInjectorError:没有 AssetResolver_Factory 的提供者!即使使用 @Injectable 并在 App.module 中提供
- python - 制作可滚动/可缩放的输出表
- typescript - TypeScript:明确定义子类型
- python - 有没有办法用布尔逻辑在 Python 中做 einsum 来优化它?