Hey, I'm stumped. Through out this post, I will bold my questions.
Is global $pdo; frowned upon? is it safe? is there a better way to access it?
As of right now, I'm using the easy way of creating a database php file and including it in specific php pages to access the $pdo variable but I would like a different approach. I would like to use a database class.
Let's say I have my class/class_database.php -- converted from a non-class.
<?php
class Database{
private $pdo;
function __construct(){
try{
$pdo = new PDO('mysql:host=HOST;dbname=DBNAME', "USER", "PASSWORD");
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo 'Connection failed: '.$e->getMessage();
}
}
}
?>
I would like to create a separate class called Statements:
class Statements{
function select($sql,$arr){
$stmt = $this->pdo->prepare($sql);
if(empty($arr) == false){
foreach($arr as $k => $v){
$stmt->bindValue($k, $v);
}
}
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}
The problem I'm having is that I would have to use extends in order to access the private pdo:
class Statements extends Database
Is extending a Database class safe or recommended? If not, how can I use a construct inside of Statements to obtain the Database Class PDO variable? Because every time Statements is called, it will need to use the pdo from the Database Class.
class Statements{
private $pdo;
function __construct(Database $newPDO){
$this->pdo = $newPDO;
}
//functions below...
}
How exactly do I pass the pdo to the __construct function and make the call? I would easily assume that creating a get function inside of the Database Class to get the private $pdo variable is risky business.
After doing a bunch of research online, it seems like programmers fight over global pdo variables and extends of the Database because it logically doesn't make sense. Unfortunately, I have yet to find a reasonable answer. I appreciate your time!