0

I have this array:

$people = array( 
   'kids' => 100, 
   'adults' => function() {
       return 1000
   }
);

If I do print_r($people) I get:

Array ([kids] => 100, [adults] => Closure Object() )

How do I get - at that same array position - the return value of the closure object instead of the Closure Object itself?

Is this possible in PHP ?

2
  • $people['adults']()? if you want the actual value in the array, though, why have a closure in the first place? Commented Nov 13, 2015 at 22:01
  • because the value has to be computed and I wanted to have the function calculating it in there Commented Nov 13, 2015 at 22:06

1 Answer 1

1
$myFunction = function() { return 1000; };
$people = array( 'kids' => 100, 'adults' => $myFunction());

If you try to do it inline like this:

$people = array( 'kids' => 100, 'adults' => function() { return 1000; }());

You will get a parse error:

PHP Parse error: syntax error, unexpected '(', expecting ')'

If you must do it on one line, you can use call_user_func:

$people = array( 
    'kids' => 100, 
    'adults' => call_user_func(function(){ return 1000; })
);
Sign up to request clarification or add additional context in comments.

3 Comments

I thought of that, but if I use call_user_func I get: Fatal error: Using $this when not in object context
I know why I get that error but still can fix it: it's because the closure is calling $this->input->post('account') (I am using Code Igniter) ...
Anyway, without taking into consideration the complications of my specific use case, your answer is correct, so marking it as such. Thanks!

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.