Variable type validation
I have methods which parameters can only handle certain types 开发者_高级运维of variable. I have a few ideas on how to validate these type and I need your help to choose the best way.
I could:- Just return
false
if one of the types of variable is wrong, without letting the user know what's happening. Plus, if the function's output isn't usually checked by the user--e.g.ob_start()
--they won't know it's even wrong; - Throw a custom
InvalidArgumentException
saying "Type of parameter X is incorrect." Thus I have to check every single parameter, making the code unreadable. Plus, the exception actually has to be catched, and I dislike thesetry...catch
in my code. - Call
error_log()
. But yet I have to check every single parameter.
What option would you choose? Why? Otherwise, do you have a better idea?
UPDATE
When I talk about types, I mean these: http://php.net/manual/en/language.types.phpThe only way to do type checking in php is using the built-in function. You can find a list here : http://www.php.net/manual/en/ref.var.php It's a real pain in the ass, but you have no choice.
For the checking itself, I'll check all the parameters type at the beginning of the function and throw an error if not. Then you can always add some debuging print_r to discover the culprit.
If you are talking to arguments passed in your code of course you MUST log errors and fix every possibile mistakes in your code.
Example:
function(){
if (!is_array($arg))
trigger_error();
}
OR
Using only objects you can specify the type of arguments
Example:
function yay(Class1 $arg1, Class2 $arg2){
//That's it!
}
精彩评论