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.
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.
On
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)
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:
As a one-liner: