views:

350

answers:

2

In PHP, depending on your error reporting level, if you don't define a constant and then call it like so:

<?= MESSAGE ?>

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

So, I wrote the following function to get around this problem, but I wanted to know if you know a way to do it in faster code? I mean, when I did a speed test without this function, I can define and dump 500 constants in .0073 seconds. But use this function below, and this switches to anywhere from .0159 to .0238 seconds. So, it would be great to get the microseconds down to as small as possible. And why? Because I want to use this for templating. I'm thinking there simply 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) ?>
A: 

try

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

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

Ray
If you run that code (oh, and add another paren on the end), you get an error 'can't use function return value in a write context' and is complaining about the constant($constant) function being passed directly to isset().
+5  A: 

As long as you don't mind using quotes on 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's no way around it without catching the notice thrown by using an undefined constant.

enobrev