5

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.

Bakaburg
  • 3,165
  • 4
  • 32
  • 64
  • 1
    "Code is totaly random." a very unlikely combination of letters to come from any kind of random generation –  Sep 05 '12 at 00:06
  • @PeeHaa yes, it returns Closure::__set_state(array( )) since closures are instances of the Closure class. – Bakaburg Sep 05 '12 at 00:21

1 Answers1

1

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);
Community
  • 1
  • 1
zamnuts
  • 9,492
  • 3
  • 39
  • 46
  • one side question: why you put $ before ID into (get_post()->$ID)? and the parenthesis are needed? – Bakaburg Sep 05 '12 at 00:31
  • 1
    @Bakaburg my bad on the $ before the ID, i have updated the post with proper syntax. also the parens are most likely not needed, i just didn't test my code and was playing it safe :) – zamnuts Sep 05 '12 at 00:32
  • 1
    please consider memory leaks when using this type of notation: http://stackoverflow.com/a/6657911/1481489 (although it has been fixed in 5.3.10) and also general memory overhead and speed: http://dboskovic.typepad.com/david-boskovic/2010/04/php-anonymous-function-benchmarks.html – zamnuts Sep 05 '12 at 00:38