0

I have db connection code:

define('DBDRIVER', 'mysql');
    define("DBHOST", "localhost");
    define("DBNAME", "dbname");
    define("DBUSER", "username");
    define("DBPASS", "password");

    $dboptions = array(
        PDO::ATTR_PERSISTENT => FALSE,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
    );

    try {       
        $PDO = new PDO(DBDRIVER . ':host=' . DBHOST . ';dbname=' . DBNAME, DBUSER, DBPASS, $dboptions);
        $PDO -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $PDO -> setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
    } catch(PDOException $e) {
        echo "Connection failed: " . $e -> getMessage();
    }

and have a class.

How to use PDO variable in my class? Can I use Global Variable but not work in class? There have any system to use this PDO variable in class (DO not define any class or constructor for PDO connection) ?

Md. Himel Ali
  • 301
  • 2
  • 10
  • Check this answer: http://stackoverflow.com/questions/20019812/database-connection-with-pdo-and-singleton-class (searched for PDO singleton). – Aziz Saleh Aug 15 '15 at 04:50

1 Answers1

1
class MyDb{
    public $pdo;
    private static $instance;

    public function __construct(PDO $pdo){
        $this->pdo = $pdo;
    }

    public static function getInstance()
    {
        if (!isset(self::$instance))
        {
            $object = __CLASS__;
            self::$instance = new $object;
        }
        return self::$instance;
    }

}

$query = MyDb::getInstance()->pdo->query('SELECT * FROM ...');

Sofiene Djebali
  • 4,398
  • 1
  • 21
  • 27
  • I already know that. But It is need to pass parameter by class. I want to define global pdo for use in any class just write pdo variable. – Md. Himel Ali Aug 15 '15 at 04:49