0

I know I can do this:

 $myFunc = function () { return 42; };
 $val = $myFunc();

But I want to skip $myFunc and do something like this:

 $val = () { return 42; };

Is this possible?

Of course, my real function is more complicated. It looks like this:

function () use ($value) { 
             $a = $value['foo'] ?: ''; 
             $d = ['FOO' => 'F', 'BAR' => 'B', '' => ''];        
             return $d[$a];
         }

And I want to use it inside a dictionary, like:

$foobar = [
    'something' = function () use $(value) { ...

Am I onto something here? Or am I using the completely wrong approach? My alternatives, which I do not prefer is:

  1. Declaring these functions as regular functions
  2. Calculate the value before the dictionary and assign it later
klutt
  • 30,332
  • 17
  • 55
  • 95

1 Answers1

1

Sure, you can wrap the function expression in parentheses and then immediately call it by appending ():

$val = (function () { return 42; })();
trincot
  • 317,000
  • 35
  • 244
  • 286