Should you check parameter types in PHP functions?

I'm used to checking the type of my parameters when writing functions. Is there a reason or against it? As an example, it would be good practice to keep a line check in this code or delete it, and why?

function rmstr($string, $remove) { if (is_string($string) && is_string($remove)) { return str_replace($remove, '', $string); } return ''; } rmstr('some text', 'text'); 

There are times when you can expect different types of parameters and run different code for them, and in this case the check is important, but my question is that we must explicitly check the type and avoid the error.

+7
source share
5 answers

My opinion is that you should perform such a check if you accept input from the user. If these lines were not received from the user or were sanitized by the user, then the verification will be excessive.

+5
source

Yes, everything is in order. However, php is not very typified to begin with, so I think this is not very useful in practice.

Also, if you use an object other than a string, the exception is more informative; so I would try not only to return an empty string at the end, because it does not semantically explain that calling rmstr (array, object) returns an empty string.

+6
source

As for me, enter the actual data authentication received from the user at the top level of abstraction, but after that, when you call most of your functions, you should now type them, and do not check them in each method, This affects performance and readability .

Note. You can add information what types are allowed for arguments to your functions using phpDoc

+2
source

It seems that local people understood this question as “If you check the parameters”, where it was “If you check the parameter types ”, and ridiculous answers and comments were taken from it.

Personally, I never check the types of operands and have never experienced any problems.

+1
source

It depends on what code you produce. If this is really production code, you should make sure that your function works properly under any circumstances. This includes verifying that the parameters contain the data that you are expecting. Otherwise, throw an exception or perform another form of error handling (that your example is completely missing).

If this is not for use in production, and you do not need to protect the code, you can ignore everything and follow the principle of "garbage in garbage" (or the three principles of crap: bone crap, process crap, get crap).

In the end, it all depends on meeting expectations: if you do not need your function to work correctly, you do not need to code it correctly. If you really rely on the fact that your code works exactly, you even need to check the input data for each block (function, class).

0
source

All Articles