0

In PHP closures are quite useful. But can I use closures to set array elements?

$configs = [
    "y" => "1",
    "x" => function() { return "xxx"; },
];
echo $configs["y"];
echo $configs["x"];  // error

gives

Recoverable fatal error: Object of class Closure could not
be converted to string on line 6 (last line)

Is there a chance to cast the closure or anything the like that the closure works for array initialization?

Working with PHP 7.1.4 on MacOSX

WeSee
  • 3,158
  • 2
  • 30
  • 58
  • maybe this answer help you https://stackoverflow.com/a/9443941/1779650 – Joe RR Mar 03 '19 at 19:56
  • Not really. I want to execute the closure immediately to get the array element initialized. I don't need the closure function later on in the code. – WeSee Mar 03 '19 at 20:00

2 Answers2

2

You want an IIFE (Immediately Invoked Function Expression):

$configs = [
  'y' => '1',
  'x' => (function () { return 'xxx'; })()
];

echo $configs['x'];

Demo: https://3v4l.org/O0fEm

Jeto
  • 14,596
  • 2
  • 32
  • 46
0

I would define the function apart:

function test(){   
    echo "Hello";
}

And then assign the result to a variable:

$a = test();
echo $a; //Returns "Hello"
alex55132
  • 177
  • 1
  • 14