我有一个简单的类,允许我写入任何日志文件:
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class Mylog
{
public function __construct($log, $level = 'debug')
{
$this->monolog = new Logger($log);
$level = constant('Logger::'.strtoupper($level));
$this->monolog->pushHandler(new StreamHandler(storage_path('logs/'.$log.'-'.date('Y-m-d').'.txt')), $level);
}
public function __call($method, $arguments)
{
$this->monolog->{$method}($arguments[0]);
}
}
这给了我错误:constant():找不到常量Logger :: DEBUG
但是,当推送处理程序时,如果我用简单的Logger :: DEBUG替换$ level,它就可以工作。事实上,为什么它没有找到常数呢?
答案 0 :(得分:2)
类似于constant()
函数的参数中的字符串内的类名必须是完全限定的。当你执行Logger :: DEBUG时,它的工作原理是use'd
,所以它解析为Monolog\Logger::DEBUG
,但在字符串中它只是Logger::DEBUG
,显然不存在。
因此,解决方案只是在字符串中使用完全限定名称,即
$level = constant('Monolog\Logger::'.strtoupper($level));