断言一组参数是没有is_string()的字符串


Assert a set of arguments are strings without is_string()?

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.');
    }

这对于两个参数是可以的…但是对于例如7个论点,它就变得荒谬了。有更好的处理方式吗?

有没有更好的处理方法?

不检查。调用者小心。

如果可能的话,我会这样做:

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..

不完全是。如果它们是对象或数组,可以(通过参数签名),但不能是字符串。

你可以这样做:

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.");
        }
    }

但实际上,通常将参数简单地转换为您需要的类型会更好:

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

或者,更简单的是,就像使用字符串一样使用参数,PHP会(通常)自动将它们转换为字符串。大多数时候,你真的不应该担心PHP变量是一个数字还是一个字符串。如果你把它当作一个数字,PHP会把它当作一个数字;