php - Assert a set of arguments are strings without is_string()?
191
public static function GetDirectLoginUser($username, $password)
{
if (!is_string($username))
{
throw new InvalidArgumentException('Usernames must be strings.');
}
if (!is_string($password))
{
throw new InvalidArgumentException('Passwords must be strings.');
}
This is fine for two arguments... but for e.g. 7 arguments it becomes ridiculous. Is there a better way of handling that?
Answer
Solution:
Don't check. Caller beware.
Answer
Solution:
I'd do something like this, if possible for your case:
Answer
Solution:
Not really. If they were objects or arrays yes (through the argument signature), but not strings.
Answer
Solution:
You could always do this:
But really, usually it would be better to simply cast the arguments into the type you need:
Or, easier yet, just use the arguments as if they were strings, and PHP will (usually) convert them to strings automatically. Most of the time, you really shouldn't worry about whether a PHP variable is, say, a number or a string — if you use it as a number, PHP will treat it as a number; if you use it as a string, PHP will treat it as a string.