Reputation: 3737
Is it possible to execute an anonymous function (also, defined inside the array) from inside the of the array ?
return [
//execute?
function() {
//logic
}
];
Or should I define it outside and only then call it?
Upvotes: 2
Views: 527
Reputation: 92854
You can also achieve this using call_user_func
function:
function test(){
return [
call_user_func(function(){
return "I was executed inside array! wow!";
})
];
}
print_r(test());
// the output:
Array
(
[0] => I was executed inside array! wow!
)
Upvotes: 2
Reputation: 437336
Technically, you can enclose the function in parentheses and invoke it like this:
return [
(function() { return 42; })()
];
which is the same as
return [
42
];
However, why would you want to do this? It will only serve to make the code less readable. It would be much better to simply have a separate variable that holds the closure and invoke that as required instead.
Upvotes: 3