PDO using singleton stored as class properity
- by Misiur
Hi again.
OOP drives me crazy. I can't move PDO to work. Here's my DB class:
class DB extends PDO
{
public function &instance($dsn, $username = null, $password = null, $driver_options = array())
{
static $instance = null;
if($instance === null)
{
try
{
$instance = new self($dsn, $username, $password, $driver_options);
}
catch(PDOException $e)
{
throw new DBException($e->getMessage());
}
}
return $instance;
}
}
It's okay when i do something like this:
try
{
$db = new DB(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
}
catch(DBException $e)
{
echo $e->getMessage();
}
But this:
try
{
$db = DB::instance(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
}
catch(DBException $e)
{
echo $e->getMessage();
}
Does nothing. I mean, even when I use wrong password/username, I don't get any exception.
Second thing - I have class which is "heart" of my site:
class Core
{
static private $instance;
public $db;
public function __construct()
{
if(!self::$instance)
{
$this->db = DB::instance(DB_TYPE.':hpost='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
}
return self::$instance;
}
private function __clone() { }
}
I've tried to use "new DB" inside class, but this:
$r = $core->db->query("SELECT * FROM me_config");
print_r($r->fetch());
Return nothing.
$sql = "SELECT * FROM me_config";
print_r($core->db->query($sql));
I get:
PDOStatement Object ( [queryString] => SELECT * FROM me_config )
I'm really confused, what am I doing wrong?