如何初始化类中的PDO连接,以便该类中的其他方法可以访问该连接

时间:2015-10-14 12:10:18

标签: php pdo

我尝试在课堂上使用PDO连接,但我似乎无法正确使用它。

class core{

    public $dbh;

    public function __construct(){
       try {
        $dbh = new PDO('mysql:host=localhost;dbname=sales;charset=utf8', 'root', '0150000048785', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::  ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        } catch (PDOException $e){
            echo $e->getMessage();
        }
    }

课堂内的另一种方法"核心&#34 ;;

public function varify_pwd(){

                    $varify = $this->dbh->prepare("SELECT * FROM users WHERE uid = ?");
                    self::bindParams($varify, array($_SESSION['uid']), $dbh);
                    $row = $varify->fetch();                    

                    if (password_verify($pwd, $row['pwd'])){ 
                        return true;
                        exit;
                    } else {
                        return false;
                        exit;   
                    }
    }
}

如何让变量$ dbh可用于其他方法?

1 个答案:

答案 0 :(得分:1)

class core{

public $dbh;

public function __construct(){
   try {
    //see here:
    $this->dbh = new PDO('mysql:host=localhost;dbname=sales;charset=utf8', 'root', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::  ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    } catch (PDOException $e){
        echo $e->getMessage();
    }
}