I have a function that returns false for many reasons. Is it possible to also make it throw catchable errors without breaking other code relying on it being true or false?
Or will I have to return arrays or return error resasons and only true on success?
What is the best aproach for this?
Some idea based on Daniel’s approach:
__FUNCTION__ should return the functions name
$errors = array();
function someFunction(){
if(ErrorTWOhappened()){
global $errors[__FUNCTION__] = "ERRORtwo";
return false;
}
if(someOtherError()){
global $errors[__FUNCTION__] = "someOtherError";
return false;
}
return true;
}
if(!someFunction())echo $errors['someFunction'];
In order not to break backwards compatibility but to provide more information, you can create a second function to log error messages. In a procedual approach, this could look like this:
And just call
myFunctionSetError('whatever');inside your existing function. Note:myFunctionis just a prefix, name it after your real function.Note also: You could obviously use the array directly. For better maintainability, however, I recommend you using functions you can modify later on to easily change the logic behind it.
If you prefer an object oriented approach, you can also set up a class for that and prevent possible side-effects regarding the global
$myFunctionErrorsvariable.Or, if you prefer a “hacked” way, extend the function a little. By adding another function parameter with a
falsedefault value. Old function calls won’t be affected by this but you ca provide this extra parameter in your future calls.