I am very new to OOP styled PHP, and I am trying to implement PDO as well. I found this nice little class online which handles the database connection, however I have no idea how to access it from another class. Here is the code:
class PDO_DBConnect {
static $db ;
private $dbh ;
private function PDO_DBConnect () {
$db_type = 'mysql'; //ex) mysql, postgresql, oracle
$db_name = 'postGal';
$user = 'user' ;
$password = 'pass' ;
$host = 'localhost' ;
try {
$dsn = "$db_type:host=$host;dbname=$db_name";
$this->dbh = new PDO ( $dsn, $user, $password);
$this->dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch ( PDOException $e ) {
print "Error!: " . $e->getMessage () . "\n" ;
die () ;
}
}
public static function getInstance ( ) {
if (! isset ( PDO_DBConnect::$db )) {
PDO_DBConnect::$db = new PDO_DBConnect ( ) ;
}
return PDO_DBConnect::$db->dbh;
}
}
$db_handle = PDO_DBConnect::getInstance();
class Person
{
function __construct()
{
$STMT = $db_handle->prepare("SELECT title FROM posts WHERE id = ? AND author = ? LIMIT 20");
$STMT->execute(array('24', 'Michael'));
while ($result = $STMT->fetchObject())
{
echo $result->title;
echo "<br />";
}
}
}
How can I gain access to the $db_handle
variable inside of my Person class? Do i have to instantiate the variable inside of the Person class? If so, does that mean I will always have to call it as $this->db_handle
? I was hoping to avoid that. (I still only have a very basic understanding of variable scope with classes)