I'm trying to use an anonymous function inside a shorthand if else statement.
$str = (true) ? function() {
//do something
return $result;
}
:
function() {
//do something else
return $result;
};
echo $str;
This throws a Object of class Closure could not be converted to string
error since the shorthand if/else stores the function in the $str variable.
How can I get the function to execute and then have $str be set to the value that the function return?
I know that there is definitely a much easier and simpler way of doing this. But I'm stubborn and I just want my curiosity satisfied.
You can use call_user_func
$str = true ? call_user_func( function(){ return "123"; } ) :
call_user_func( function(){ return "321"; } );
That's not a "short hand if/else", it's the ternary operator. Secondly, you're not actually invoking your functions, just assigning one or the other to the variable $str
. You need to actually invoke the resulting function.
Why you'd do this, I have no idea...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With