嗨,我正在使用pdo为mysql开发一个基本的数据库连接类,但是当我var dump返回结果时,它告诉我有2个对象: object(PDO)[2]
. 不是只有一个吗?
以下是我目前的代码:
class DBConnection
{
// Settings (DSN)
protected $driver, $host, $name, $charset;
// Credentials
protected $user, $pass;
// PDO Connection
protected $connection;
public function __construct() {
require_once( 'database.config.php' );
// Settings (DSN)
$this->driver = DB_DRIVER;
$this->host = DB_HOST;
$this->name = DB_NAME;
$this->charset = DB_CHARSET;
// Credentials
$this->user = DB_USER;
$this->pass = DB_PASS;
// Initialise Connection
var_dump($this->getConnection());
}
private function getConnection() {
// Check if connection is already established
if ( $this->connection == NULL ) {
$dsn = "$this->driver:host=$this->host;dbname=$this->name;charset=$this->charset";
try {
$this->connection = new PDO($dsn,$this->user, $this->pass);
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch ( PDOException $error ) {
echo 'Connection failed: ' . $error->getMessage();
}
}
return $this->connection;
}
}
$new = new DBConnection();
配置文件:
define('DB_DRIVER', 'mysql');
define('DB_HOST', 'localhost');
define('DB_NAME', 'test');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASS', '');
1条答案
按热度按时间monwx1rj1#