Php function as function's parameter
In my php project I have some functions that in some cases I want to call under try-catch block, and in some cases not under try-catch block. And now I want to write a function that gets some function as parameter, calls it and return false in case of exception.
Approximately code like this and with support of different numbers of parameters for 'someFunction'.
function tryTo($someFunctionName) {
try {
return someFunctionName();
} catch (Exception $error) {
return false;
}
How to organize that?
Answer
Solution:
You need to define your original functions as Closures so they are represented by variables and can be passed as function arguments.
Here is example code:
As of PHP 5.6 you can also use the spread operator which makes it a piece of cake to support multiple arguments. That way one
tryIt
function can host for functions with different numbers of parameters:Answer
Solution:
PHP allows you to call a number of things as if they were functions - this includes:
"myFunc"
)["myFunc", ["arg1", "arg2"]]
)[new MyClass(), ["arg1", "arg2"]]
)__invoke()
magic methodAll of these can be denoted by the
callable
typehint. As such, implementing your function as such:would allow you to use
tryTo()
for anything PHP considers callable, and enforce that whatever you pass can be used to call a function.So the following will work:
You can see here for more information.
That said, I'm seriously questioning the use case for a function like that - generally, exceptions shouldn't happen unless something is wrong, and using a function like that opens you up to silent failures. At the very least, you should log the exception that occurred so you can see that something went wrong, but in my opinion you should handle specific exceptions wherever they're relevant. That, however, is an entirely different discussion altogether and does nothing to answer your question.
Answer
Solution: