I want to call an anonymous function without declaring a variable for it.
I know this is a working example:
$foo = function ($bar) use ($foo) { if (is_array($bar)) { foreach ($bar AS $current) { $foo($current); } } else { print($bar); } }; $foo($input);
But I want to call and disable it automatically:
call_user_func(function ($bar) { if (is_array($bar)) { foreach ($bar AS $current) {
But this example will not work, because our function does not have a name. Is there any solution or do you know any solution to solve this problem?
PS: Suppose that $input is the following array: ["Hello, ", "World!"] .
The conclusion should be:
Hello, World!
Update # 1:
As soon as this is an example, call_user_func_array(function () { ... }, $input) not the solution I'm looking for.
And it will not work if I have $input like [["Hello, ", "World"], "!"] .
Update # 2:
Another solution I'm not looking for is debug_backtrace()[1]['args'][0]->__invoke($current); . I think this is ugly enough to be used for debugging only. :) Thanks @fschmengler .
And another form of this call_user_func(debug_backtrace()[1]['args'][0], $current)); .
Update # 3:
Another solution written by @UlrichEckhardt injects an anonymous function into another anonymous function. I think by canceling a previously declared function variable - for example. the first example is cleaner and shorter. But this is also a solution.
function () { $f = function ($param) use ($f) {