1

对于自定义记录器,我想强制调用者传递在Psr\Log\LogLevel.

此类定义如下:

namespace Psr\Log;
/**
 * Describes log levels.
 */
class LogLevel
{
    const EMERGENCY = 'emergency';
    const ALERT     = 'alert';
    const CRITICAL  = 'critical';
    const ERROR     = 'error';
    const WARNING   = 'warning';
    const NOTICE    = 'notice';
    const INFO      = 'info';
    const DEBUG     = 'debug';
}

记录器的功能(错误)如下所示:

public static function log($log, LogLevel $logLevel = null): void {
   // .....
}

这不起作用,因为 LogLevel::DEBUG 例如是一个字符串而不是类的实例。有没有办法在 PHP 类型声明中强制使用类常量?因为如果我定义string那么你显然可以传递任何字符串,但我只想允许声明的常量。

4

3 回答 3

2

PHP 没有固定的限制,只有类型。

但是你可以做一个这样的解决方法:

class LogLevel
{
    protected string $logName;

    private function __construct(string $logName)
    {
        $this->logName = $logName;
    }
    public function getName(): string
    {
        return $this->logName;
    }

    public static function emergency(): self
    {
        return new self('emergency');
    }

    public static function alert(): self
    {
        return new self('alert');
    }

    public static function critical(): self
    {
        return new self('critical');
    }
    // create the other constants here
}

现在你的静态功能工作

public static function log($log, LogLevel $logLevel = null): void {
   // .....
}

$logLevel将收到LogLevel::emergency(),LogLevel::critical()等,您可以通过调用获得关卡名称$logLevel->getName()

于 2020-12-10T11:46:05.837 回答
0

如果您有 Phpstorm,您可以使用新的#[ExpectedValues]属性功能:https ://blog.jetbrains.com/phpstorm/2020/10/phpstorm-2020-3-eap-4/#expectedvalues_examples

于 2020-12-10T11:27:10.800 回答
0

没有简单的方法,但您可以检查插入的字符串是否与某些值匹配

function checkLog(string $logLevel){
  $acceptableValues = array("emergency", "error", "debug");
  if(!in_array($logLevel, $acceptableValues) die();
}

用你的类的常量替换数组中的字符串。

于 2020-12-10T11:34:35.323 回答