Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you verify parameter types in PHP functions?

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.

like image 953
Aram Kocharyan Avatar asked Sep 20 '11 00:09

Aram Kocharyan


1 Answers

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.

like image 171
Candide Avatar answered Oct 01 '22 12:10

Candide