将常量传递给PHP方法的最佳方法是使用范围解析操作符(::)


The best way to pass a constant to a PHP method with Scope Resolution Operator (::)

我正在寻找最好的方式来传递一个常数的方法PHP 5.4

我需要动态修改一个类的常量。

实际上我做了这个:

//  Analog::handler('Analog'Handler'Threshold::init('Analog'Handler'File::init($log_file)),Analog::<CONSTANT_I_NEED_PASS>>);
switch ($config['debug']) {
case 0:
case 1:
case 2:
    Analog::handler('Analog'Handler'Threshold::init('Analog'Handler'File::init($log_file)),Analog::CRITICAL);
    break;
case 3:
case 4:
case 5:
    Analog::handler('Analog'Handler'Threshold::init('Analog'Handler'File::init($log_file)),Analog::NOTICE);
    break;
case 6:
case 7:
    Analog::handler('Analog'Handler'Threshold::init('Analog'Handler'File::init($log_file)),Analog::DEBUG);
    break;

}

我认为有一个最好的方法。

可以使用constant():

实现变量常量名
$constantToPass = 'CRITICAL';
Analog::handler(
    'Analog'Handler'Threshold::init('Analog'Handler'File::init($log_file)),
    constant(''Analog'Handler'File::' . $constantToPass));

从PHP 5.5开始,您还可以使用::class来代替硬编码类名,从而利用命名空间解析:

use Analog;
$constantToPass = 'CRITICAL';
Analog::handler(
    Analog'Handler'Threshold::init(Analog'Handler'File::init($log_file)),
    constant(Analog::class . '::' . $constantToPass));

但我会认为这是"最好的方法"!看起来您正在尝试删除重复。这个方法怎么样:

switch ($config['debug']) {
case 0:
case 1:
case 2:
    $severity = Analog::CRITICAL;
    break;
case 3:
case 4:
case 5:
    $severity = Analog::NOTICE;
    break;
case 6:
case 7:
    $severity = Analog::DEBUG;
    break;
}
Analog::handler(
    'Analog'Handler'Threshold::init('Analog'Handler'File::init($log_file)),
    $severity);

不能修改或改变常量变量的值。您可以使用self关键字将常量传递给方法。

 self::constant_name;