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?

518

Answer

Solution:

Is there a better way of handling that?

Don't check. Caller beware.

697

Answer

Solution:

I'd do something like this, if possible for your case:

public static function someMethod($username, $password, $something, $else)
{
    foreach( array( 'username', 'password', 'something', 'else' ) as $mustBeString )
    {
        // using variable variable here
        // who would have thought I'd ever propose that :)
        if( !is_string( $$mustBeString ) )
        {
            throw new InvalidArgumentException( ucfirst( $mustBeString ) . 's must be strings.');
        }
    }

    // etc..
122

Answer

Solution:

Not really. If they were objects or arrays yes (through the argument signature), but not strings.

640

Answer

Solution:

You could always do this:

public static function GetDirectLoginUser($username, $password)
{
    foreach (array("username" => $username, "password" => $password) as $name => $arg)
    {
        if (!is_string($arg))
        {
            throw new InvalidArgumentException("The $name must be a string.");
        }
    }

But really, usually it would be better to simply cast the arguments into the type you need:

public static function GetDirectLoginUser($username, $password)
{
    $username = (string) $username;
    $password = (string) $password;

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.

People are also looking for solutions to the problem: javascript - AJAX XMLHttpRequest 'bouncing back' when sending vars to PHP

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.