red-o-alf
red-o-alf

Reputation: 3245

Array item is a closure object, can I get its return value as the same array item?

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 ?

Upvotes: 0

Views: 926

Answers (1)

Jeff Lambert
Jeff Lambert

Reputation: 24661

$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; })
);

Upvotes: 1

Related Questions