Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I immediately evaluate an anonymous function? [duplicate]

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

like image 686
Tom Avatar asked Nov 05 '22 06:11

Tom


1 Answers

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).

like image 199
rdlowrey Avatar answered Nov 07 '22 22:11

rdlowrey