Home » Php » Should you verify parameter types in PHP functions?

Should you verify parameter types in PHP functions?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m used to the habit of checking the type of my parameters when writing functions. Is there a reason for or against this? As an example, would it be good practice to keep the string verification in this code or remove 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 may expect different parameter types and run different code for them, in which case the verification is essential, but my question is if we should explicitly check for a type and avoid an error.

How to&Answers:

My opinion is that you should perform such verification if you are accepting input from the user. If those strings were not accepted from the user or are sanitized input from the user, then doing verification there is excessive.

Answer:

Yes, it’s fine. However, php is not strongly typed to begin with, so I think this is not very useful in practice.

Additionally, if one uses an object other than string, an exception is a more informative; therefore, I’d try to avoid just returning an empty string at the end, because it’s not semantically explaining that calling rmstr(array, object) returns an empty string.

Answer:

As for me, type checking actual to data, getted from user on top level of abstraction, but after that, when You call most of your functions you already should now their type, and don’t check it out in every method. It affects performance and readability.

Note: you can add info, which types is allowed to arguments for your functions by phpDoc

Answer:

It seems local folks understood this question as “Should you verify parameters” where it was “Should you verify parameter types“, and made nonsense answers and comments out of it.

Personally I am never checking operand types and never experienced any trouble of it.

Answer:

It depends which code you produce. If it’s actually production code, you should ensure that your function is working properly under any circumstances. This includes checking that parameters contain the data you expect. Otherwise throw an exception or have another form of error handling (which your example is totally missing).

If it’s not for production use and you don’t need to code defensively, you can ignore anything and follow the garbage-in-garbage-out principle (or the three shit principle: code shit, process shit, get shit).

In the end it is all about matching expectations: If you don’t need your function to work properly, you don’t need to code it properly. If you are actually relying on your code to work precisely, you even need to validate input data per each unit (function, class).