如果函数没有返回true,如何正确返回并显示字符串值?

时间:2013-09-16 15:28:13

标签: php oop methods return

我正在尝试编写一个检查用户是否存在的方法,并进行一些验证。

这是到目前为止的代码:

public function checkUsername(){
            if((strlen($_POST['register-username']) > 2) && (strlen($_POST['register-username']) < 16)){
                $stmt = $this->dbh->prepare("SELECT username FROM adrenaline_junkies_uk_users WHERE username = ?");
                $stmt->bindParam(1, $this->post_data['register_username'], PDO::PARAM_STR);
                $stmt->execute();
                if($stmt->rowCount() != 0){
                        return TRUE;
                }else{
                    return $this->error .= '<span style="color:red;">Username already exists.</span>';
                }
            }else{
                return $this->error .= '<span style="color:red;">Username must be between 3 and 15 characters.</span>';
            }

    }

这就是我试图称呼它的方式:

if( isset($_POST['register-submit'])){

        $error = '';
        $register = new register($_POST, $dbh);
            if(!$error .= $register->checkUsername()){

                    //continue

            }else{
                $error .= $register->checkUsername();
            }
    }

要测试它,我不会在输入字段中输入任何内容来获取要返回的第一个错误并在网页上正确回显它。但没有任何东西在显示。

这是正确的做法吗?对不起,我不太熟悉在课堂上使用方法。我假设我在调用程序的初始if语句中做错了,我应该像我一样运行该方法两次吗?

1 个答案:

答案 0 :(得分:1)

使用Exceptions。像:

public function checkUsername(){
    if((strlen($_POST['register-username']) > 2) && (strlen($_POST['register-username']) < 16)){
        $stmt = $this->dbh->prepare("SELECT username FROM adrenaline_junkies_uk_users WHERE username = ?");
        $stmt->bindParam(1, $this->post_data['register_username'], PDO::PARAM_STR);
        $stmt->execute();
        if($stmt->rowCount() != 0){
                return TRUE;
        }else{
            throw new Exception("Username already exists.");
        }
    }else{
        throw new Exception("Username must be between 3 and 15 characters.");
    }

}

if( isset($_POST['register-submit'])){

    $error = '';
    $register = new register($_POST, $dbh);
    try {
        if($register->checkUsername()){
            //continue
        }
    } catch ($e) {
        $error .= '<span style="color:red;">' . $e->getMessage() . '</span>';
    }
}

您可以进行子类化:

class UsernameException extends Exception {}

try {
    throw new UsernameException("Your username is too awesome");
} catch (UsernameException $e) {
    exit($e->getMessage());
} catch (SomeOtherException $e) {
    exit("500");
} catch (Exception $e) {
    exit("que?");
}