Reputation:
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) ?>
Upvotes: 1
Views: 1053
Reputation: 22532
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.
Upvotes: 5
Reputation: 2258
try
if (isset(constant($constant)) ...
This shouldn't trigger any E_NOTICE messages, so you don't have to set and reset error_reporting.
Upvotes: -2