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.

2
  • 1
    "Code is totaly random." a very unlikely combination of letters to come from any kind of random generation Commented Sep 5, 2012 at 0:06
  • @PeeHaa yes, it returns Closure::__set_state(array( )) since closures are instances of the Closure class. Commented Sep 5, 2012 at 0:21

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

one side question: why you put $ before ID into (get_post()->$ID)? and the parenthesis are needed?
@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 :)
please consider memory leaks when using this type of notation: stackoverflow.com/a/6657911/1481489 (although it has been fixed in 5.3.10) and also general memory overhead and speed: dboskovic.typepad.com/david-boskovic/2010/04/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.