I want to optimize the validation of certain constants in PHP

In PHP, depending on the level of error reporting, if you don't define a constant then call it like this:

<?= MESSAGE ?>

      

It can print the name of the constant instead of the value!

So, I wrote the following function to work around this problem, but I wanted to know if you know how to do it in faster code? I mean, when I did a speed test without this function, I can define and reset 500 constants in 0.73 seconds. But use this function below and it switches to anywhere from 0.0159 to 0.238 seconds. So it would be great if microseconds were as small as possible. And why? Because I want to use this for templates. I think there just has to be a better way than toggling the error reporting with every variable I want to display.

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) ?>

      

+1


source to share


2 answers


As long as you don't mind using quotes for your constants, you can do this:

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

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

define('MESSAGE', 'test');

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

      

Output:



Undefined

Test

Otherwise, there is no way to get around this without noticing the notification triggered by the constant undefined.

+5


source


try it

if (isset (constant ($ constant)) ...


This shouldn't trigger any E_NOTICE messages, so you don't need to set and reset error_reporting.

-2


source







All Articles