crm*_*ham 0 php database oop pdo class
我已经开始学习如何使用OOP并创建了一个用户授权类来检查用户是否存在等.目前我使用全局变量连接到数据库,$dbh
这是一个PDO连接.我听说以这种方式使用全局变量并不是一种好的做法,但我不确定如何改进它,我只是将$dbh
变量传递给连接到数据库时需要它的方法,为什么不考虑这个好的做法?
这是我正在使用的一些代码:
调用程序中包含的数据库PDO连接:
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=localhost;dbname=oopforum","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)
需要数据库连接的类:
class Auth{
private $dbh;
function __construct(){
global $dbh;
$this->dbh = $dbh;
}
function validateLogin($username, $password){
// create query (placing inside if statement for error handling)
if($stmt = $this->dbh->prepare("SELECT * FROM oopforumusers WHERE username = ? AND password = ?")){
$stmt->bind_param(1, $username);
$stmt->bind_param(2, $password);
$stmt->execute();
// Check rows returned
$numrows = $stmt->rowCount();
//if there is a match continue
if( $numrows > 0 ){
$stmt->close();
return TRUE;
}else{
$stmt->close();
return FALSE;
}
}else{
die('ERROR: Could not prepare statement');
}
}
function checkLoginStatus(){
if(isset($_SESSION['loggedin'])){
return TRUE;
}else{
return FALSE;
}
}
function logout(){
session_destroy();
session_start();
}
}
Run Code Online (Sandbox Code Playgroud)
您应该将PDO连接传递给构造函数:
function __construct($dbh) {
$this->dbh = $dbh;
}
Run Code Online (Sandbox Code Playgroud)
该连接被称为您的类的依赖项,因为显然您的类需要它来执行其功能.好的做法要求你的班级应该明确表示这种依赖存在; 这是通过使其成为必需的构造函数参数来实现的.
如果您从全局变量中提取依赖项,则会产生以下几个问题: