Skip to content
Advertisement

The trick of the ternary operator?

Is there a way to use such a construction?

Auth::check() ?? echo "<h1>Log in please</h1>"

Auth::check checks whether the user is authorized

This trick with ternary operator would make it much easier for me to read the code

Advertisement

Answer

I think you are missing the importance of NULL in this whole thing. the ?? is afterall called the Null coalescing operator

Examples

var_dump( true ?? "<h1>Log in please</h1>" ); 
var_dump( false ?? "<h1>Log in please</h1>" );  
var_dump( NULL ?? "<h1>Log in please</h1>" );  

RESULT

bool(true)      <- operand1

bool(false)     <- operand1

string(22) "<h1>Log in please</h1>"     <- operand2

So ONLY when operand 1 in actually and specifically NULL will it return operand 2

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