Skip to content
Advertisement

Is there a fancy and short solution for using the null coalescing operator with constants in PHP?

Since PHP 8 the constant() function throws an error instead of returning null and generating an E_WARNING when the given constant is not defined, and therefore I can’t use the following code to set a variable anymore:

$foo = $SESSION['bar'] ?? constant("MY_CONSTANT") ?? "baz";

My obvious quick solution for this is changing that line to:

$foo = $SESSION['bar'] ?? (defined("MY_CONSTANT") ? constant("MY_CONSTANT") : "baz");

It honestly bothers me a little because I like how the first code is cleaner and do not force me to write ugly giant ternary sequences with a billion parentheses in case I want to add more constants to that ?? cascade. I also tried – hopeless because the (short) documentation around the null coalescing operator already stated that ?? was just a shortcut for isset() in a ternary – the following:

$foo = $SESSION['bar'] ?? MY_CONSTANT ?? "baz";

But it didn’t work – as expected. Another solution would be creating a function that returns null when the constant is not defined, such as:

function defined_constant($constant) {

    return (defined($constant) ? constant($constant) : null);

}

$foo = $SESSION['bar'] ?? defined_constant("MY_CONSTANT") ?? "baz";

I would like to know if there’s any solution without creating new functions or changing the php.ini file that would allow me use only ??s as in that first line of code.

It is ok if the answer to my question is just a “no, there is no solution”, but I’m intrigued and I can’t find much stuff about this on the internet. PHP also seems to have just a few native functions around constants (three miscellaneous functions and the get_defined_constants()?).

Advertisement

Answer

true way is detect all undefined constants and define: defined('MY_CONSTANT') || define('MY_CONSTANT', 'baz'); and etc.

if you want save this trash constructions, then you can use something like this get_defined_constants()['MY_CONSTANT'] ?? 'baz'

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement