phpechonull-coalescing-operator

Can I use echo statement immediately after a null coalescing operator?


Is there a way to implement the logic in my snippet?

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

Parse error: syntax error, unexpected token "echo"

Auth::check() checks whether the user is authorized.

This trick with null coalescing operator would make it much easier for me to read the code.


Solution

  • 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