2

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?

0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

Try this:

return [
    call_user_func(function(){
        // logic executed
    })
];

Comments

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.