Php computes a variable on the fly using anonymous functions

Sometimes when you initialize variables, you want to pass them too complex values ​​to calculate in one command, so you usually either evaluate the dummy variable before, and then pass its value or define a function in another place and pass it, return the value of our variable.

My question (desire): is it possible to compute a variable on the fly using anonymous functions?

for example, instead:

$post = get_post();
$id = $post->ID;

$array = array(
    'foo' => 'hi!',
    'bar' => $id
);

Let's use something like this:

$array = array(
    'foo' => 'hi!',
    'bar' => (function(){
        $post = get_post();
        return $post->ID;
    })
);

The code is summary random.

+5
source share
1 answer

In your example, the following will be fine:

$array = array('foo'=>'hi!','bar'=>(get_post()->ID));

, , fooobar.com/questions/65285/....

$a = array('foo' => call_user_func(
    function(){
        $b = 5;
        return $b;
    })
);
var_dump($a);
+1

All Articles