Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php computing a variable on the fly using anonymous functions

Sometimes while initializing variables, you want to pass them values that are too complex to be computed in a single command, so you usually either compute a dummy variable before and then pass its value, or define a function elsewhere, and pass it's return value to our variable.

My question (wish) is, is it possible instead compute to a variable on the fly using anonymous functions?

for example, instead of use this:

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

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

Lets use something like this:

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

Code is totaly random.

like image 986
Bakaburg Avatar asked Nov 13 '22 23:11

Bakaburg


1 Answers

In your example, the following would do just fine:

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

However, with consideration to your question being a bit more open ended and not specific to your code snippet, you may find this stackoverflow answer acceptable.

$a = array('foo' => call_user_func(
    function(){
        $b = 5;
        return $b;
    })
);
var_dump($a);
like image 141
zamnuts Avatar answered Nov 15 '22 12:11

zamnuts