5

Possible Duplicate:
Immediately executing anonymous functions

I want to immediately evaluate an anonymous function rather than it appearing as a Closure object in method args. Is this possible?

For example:

$obj = MyClass;
$obj->Foo(function(){return "bar";}); // passes a Closure into Foo()
$obj->Foo(function(){return "bar";}()); // passes the string "bar" into Foo()?

The 3rd line is illegal syntax -- is there any way to do this?

Thanks

Community
  • 1
  • 1
Tom
  • 1,055
  • 2
  • 14
  • 21
  • It's hard to imagine why you would need to do this? Why not just assign result of the function to a variable and then pass that variable instead? – Dmitri Snytkine Jan 31 '12 at 20:48
  • Also in these examples your function is pretty much just an anonymous function, does not have characteristics of a closure, it's not 'remembering' any variables from its current context – Dmitri Snytkine Jan 31 '12 at 20:49
  • 1
    I realize that, I really didn't want to explain why I need to do this -- obviously it's an unusual situation. – Tom Jan 31 '12 at 20:54
  • @DmitriSnytkine, this sort of thing is done *all the time* in JavaScript – zzzzBov Jan 31 '12 at 21:05

1 Answers1

2

You could do it with call_user_func ... though that might be a bit silly when you could just assign it to a variable and subsequently invoke the variable.

call_user_func(function(){ echo "bar"; });

You might think that PHP 5.4 with it's dereferencing capabilities would make this possible. You'd be wrong, however (as of RC6, anyway).

  • Why do you consider it silly? – Tadeck Jan 31 '12 at 20:54
  • @Tadeck Well, it seems to me it doesn't make sense to perform an additional function call to `call_user_func` when you could just as easily do `$f = function() { echo '1'; }; $f();` Though there's nothing technically unsound about using `call_user_func` in this case, I find the explicit invocation more readable. I can see the appeal in the brevity of a single line with `call_user_func`, though. –  Jan 31 '12 at 21:00