Home > Software design >  Can an anonymous function be used with a null coalescing operator?
Can an anonymous function be used with a null coalescing operator?

Time:07-06

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.

CodePudding user response:

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;

CodePudding user response:

between () an anonymous function with a pair ( ) can be called directly (i am testing this from php 7.4 and the script bellow in php 8.2 alpha 3):

<?php


function br(){echo '<br>';}

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

br();


(function(){ echo 'hello'; })();
br();

var_dump((function(){ return 'my value'; })());
br();

var_dump((function($sure){ return $sure; })('custom anonymous param = my value'));
br();

$a[1] ?? (function () { echo 'z'; })();
br();
?>

imagine then an array with functions then each key value then ($ar['func1'])(); called like this ; even this is possible. (the last idea is only test purpose don't use complicate constructs in production witch will affect cpu with useless ops)

  • Related