I have started to learn how to use OOP and have created a user authorisation class to check if the user exists etc. Currently I am connected to the database by using the global variable $dbh which is a PDO connection. I’ve heard that using global variables in this way isn’t good practice but am not sure how I can improve it, would I just pass the $dbh variable into the method that requires it when connecting to a database and why exactly is this not considered good practice?
Here is some code I am using:
Database PDO connection included in calling program:
//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();
}
The class that requires the database connection:
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();
}
}
You should pass the PDO connection to the constructor:
The connection is called a dependency of your class because obviously your class needs it in order to carry out its function. Good practice dictates that your class should make it explicit that this dependency exists; this is achieved by making it a mandatory constructor parameter.
If you instead pull in the dependency from a global variable you create several issues: