当它应该返回true时返回false

时间:2013-09-16 16:23:42

标签: php oop exception methods pdo

我无法弄清楚为什么这个方法会返回false。我正在检查输入密码的长度。它肯定超过5个字符。输入字段的名称是正确的。但它总是抛出异常throw new Exception("Password must contain at least 6 characters.");

方法:

public function checkPassword(){
        if(strlen($this->post_data['register_password']) > 5){

        }else{
            throw new Exception("Password must contain at least 6 characters.");
        }
    }

致电:

if( isset($_POST['register-submit'])){  
    $error = '';
    $register = new register($_POST, $dbh);
        try {
            if($register->checkUsername()){
                if($register->checkPassword()){

                }
            }
        } catch (Exception $e) {
            $error .= '<span style="color:red;">' . $e->getMessage() . '</span>';
        }
}

编辑:添加了更多的课程

public $post_data = array();
private $dbh;
public function __construct($post_data, PDO $dbh){
        $this->error = array();
        $this->post_data = array_map('trim', $post_data);
        $this->dbh = $dbh;

    }

2 个答案:

答案 0 :(得分:2)

您使用register创建了课程$_POST,然后使用$this->post_data获取register_password。我怀疑$this->post_data是否有问题,添加var_dump进行调试:

public function checkPassword(){
    if(strlen($_POST['register_password']) > 5){
        return true;

    }else{
        // for debug
        // var_dump($this->post_data['register_password']);
        throw new Exception("Password must contain at least 6 characters.");
    }
}

添加var_dump以调试__construct

public function __construct($post_data, PDO $dbh){
    $this->error = array();
    $this->post_data = array_map('trim', $post_data);
    var_dump($this->post_data);
    $this->dbh = $dbh;
}

答案 1 :(得分:2)

尝试将var_dump($_POST)放在调用代码的顶部。确保您拥有正确的密码变量名称。我注意到您有register-submit提交按钮,register_password提供密码。您是否将连字符(-)与下划线(_)混合在一起?