我想在PHP中最佳地检查定义的常量

1 php constants

在PHP中,根据您的错误报告级别,如果您没有定义常量,然后像这样调用它:

<?= MESSAGE ?>
Run Code Online (Sandbox Code Playgroud)

它可能会打印常量的名称而不是值!

所以,我编写了以下函数来解决这个问题,但我想知道你是否知道在更快的代码中做到这一点的方法?我的意思是,当我在没有此功能的情况下进行速度测试时,我可以在.0073秒内定义并转储500个常量.但是使用下面的这个功能,这会切换到从.0159到.0238秒的任何地方.因此,将微秒降低到尽可能小是很好的.为什么?因为我想用这个来模板化.我认为只需要比我想要显示的每个变量切换错误报告更好的方法.

function C($constant) {
    $nPrev1 = error_reporting(E_ALL);
    $sPrev2 = ini_set('display_errors', '0');
    $sTest = defined($constant) ? 'defined' : 'not defined';
    $oTest = (object) error_get_last();
    error_reporting($nPrev1);
    ini_set('display_errors', $sPrev2);
    if (strpos($oTest->message, 'undefined constant')>0) {
        return '';
    } else {
        return $constant;
    }
}

<?= C(MESSAGE) ?>
Run Code Online (Sandbox Code Playgroud)

eno*_*rev 5

只要你不介意在常量上使用引号,就可以这样做:

function C($constant) {
    return defined($constant) ? constant($constant) : 'Undefined';
}

echo C('MESSAGE') . '<br />';

define('MESSAGE', 'test');

echo C('MESSAGE') . '<br />';
Run Code Online (Sandbox Code Playgroud)

输出:

未定义

测试

否则,如果没有捕获使用未定义常量引发的通知,就无法绕过它.