如何在另一个类中使用$ PDO变量?

时间:2015-08-15 04:43:03

标签: php mysql class object pdo

我有数据库连接代码:

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();
    }

并上课。

如何在班上使用PDO变量? 我可以使用全局变量但不能在课堂上工作吗? 有没有系统在类中使用这个PDO变量(不要为PDO连接定义任何类或构造函数)?

1 个答案:

答案 0 :(得分: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 ...');