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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With