PDO using singleton stored as class properity

Posted by Misiur on Stack Overflow See other posts from Stack Overflow or by Misiur
Published on 2010-05-23T10:04:49Z Indexed on 2010/05/23 10:10 UTC
Read the original article Hit count: 253

Filed under:
|
|
|
|

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?

© Stack Overflow or respective owner

Related posts about php

Related posts about beginner