PHP allows you to call a number of things as if they were functions - this includes:
- function names as strings (for instance
"myFunc")
- arrays containing a function name as the first element and an array of arguments as the second element (for instance
["myFunc", ["arg1", "arg2"]])
- arrays containing an object as the first element and an array of arguments as the second element (for instance
[new MyClass(), ["arg1", "arg2"]])
- instances of classes implementing the
__invoke() magic method
- Closures/anonymous functions
All of these can be denoted by the callable typehint. As such, implementing your function as such:
tryTo(callable $callable) {
try {
$callable();
catch(\Exception $ex) {
return false;
}
}
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:
tryTo('myFunc'); // Equivalent to myFunc();
tryTo('MyClass::myFunc'); // Equivalent to MyClass::myFunc();
tryTo(['myFunc', ['myArg', 'myOtherArg']]; // Equivalent to myFunc('myArg', 'myOtherArg');
tryTo([new MyClass(), 'myFunc']); // Equivalent to (new MyClass())->myFunc();
tryTo(function() { echo 'test'; }); // executes whatever closure you pass
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.