WeSee
WeSee

Reputation: 3770

PHP: closure to set variable

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

Upvotes: 0

Views: 631

Answers (2)

Jeto
Jeto

Reputation: 14927

You want an IIFE (Immediately Invoked Function Expression):

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

echo $configs['x'];

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

Upvotes: 2

alex55132
alex55132

Reputation: 177

I would define the function apart:

function test(){   
    echo "Hello";
}

And then assign the result to a variable:

$a = test();
echo $a; //Returns "Hello"

Upvotes: 0

Related Questions