数组项是一个闭包对象,我可以将其返回值作为相同的数组项吗?

数组项是一个闭包对象,我可以将其返回值作为相同的数组项吗?

问题描述:

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 ?

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