Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand if else and anonymous functions

Tags:

php

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.

like image 765
Vitaliy Isikov Avatar asked Oct 17 '25 13:10

Vitaliy Isikov


2 Answers

You can use call_user_func

$str = true ? call_user_func( function(){ return "123"; } ) : 
              call_user_func( function(){ return "321"; } ); 
like image 161
Orangepill Avatar answered Oct 19 '25 02:10

Orangepill


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...

like image 41
meagar Avatar answered Oct 19 '25 04:10

meagar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!