Search code examples
phpanonymous-functionnull-coalescing-operator

Can an anonymous function be used with a null coalescing operator?


I'm trying to supply a function as the false choice with a null coalescing operator.

Example:

$a = [0 => 'x'];
$value = $a[1] ?? (function () { return 'z'; });

What I receive as a return is {closure} containing scope ($this) instead of the value.


Solution

  • Your code will work. You probably have an error when using $value later in code. You need to check if $value contains a closure, and if yes, it needs to be executed to get the string:

    $a = [0 => 'x'];
    $value = $a[1] ?? fn() => 'z';
    // fn() => 'z'
    // ... is the arrow notation of:
    // function () { return 'z'; };
    
    if ($value instanceof \Closure) {
      echo $value();
    } else {
      echo $value;
    }
    

    As a one-liner:

    echo $value instanceof \Closure ? $value() : $value;