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

2
  • maybe this answer help you stackoverflow.com/a/9443941/1779650 Commented Mar 3, 2019 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. Commented Mar 3, 2019 at 20:00

2 Answers 2

2

You want an IIFE (Immediately Invoked Function Expression):

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

echo $configs['x'];

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

Sign up to request clarification or add additional context in comments.

2 Comments

Can we invoke the closure during definition in line 3? How?
@WeSee Yes. See my edit for an alternative version using an IIFE (PHP 7 only).
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"

2 Comments

In my case that doesn't work. I have a config-Array where array variables are being set...
Then edit your post and show us what do you have so we can help you with more precision ^^ @WeSee

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.