class connector {
private static $db;
function __construct() {
$this->db = null;
$this->connect();
}
private function connect() {
$this->db = new PDO('mysql:host=localhost;dbname=database;charset=utf8','user','pass');
}
public static function getDB() {
if (!isset(self::$db)) {
self::$db = new connector();
}
return self::$db;
}
EDITED
// this was my original function, I had reduced it for less space. my deepest regrets, I won't do it again.
public function getValue($sql,$val='') {
if ($val != '') {
$data = $this->db->prepare($sql);
$data->execute($val);
return $data->fetch(PDO::FETCH_COLUMN);
}
else {
return $this->db->query($sql)->fetch(PDO::FETCH_COLUMN);
}
using this class I can easily use the pdo database object from anywhere, with custom functions.
$db = connector::getDB();
// var_dump()
db:object(connector)#1 (1) {
["db":"connector":private]=>
object(PDO)#2 (0) {
}
}
$db->getValue('SELECT foo FROM bar'); //succeeds
$db->query('SELECT foo FROM bar'));
// throws
// Fatal error: Call to undefined method connector::query()
if I return the actual object param instead of the whole object:
return self::$db->db;
db:object(PDO)#2 (0) {
}
the queries exchange roles
$db->getValue('SELECT foo FROM bar');
// throws
// Fatal error: Call to undefined method connector::getValue()
$db->query('SELECT foo FROM bar')); //succeeds
How can I have both with the same object, effectively using $db->query()
and $db->getValue()
in the same script.