我有以下数据库类。我的想法是,这将检查该类的现有实例并返回该实例,而不是创建新的数据库连接。通过PHP的MySQL数据库连接的单个实例类
当我运行代码时,它创建了一个连接。当我刷新页面时,会创建另一个连接(检查MySQL连接)。
我的想法不对吗?相当新的使用面向对象的新手问题!
任何帮助或指针在正确的方向将不胜感激。
非常感谢。
<?php
class Db
{
private $_connection;
private static $_instance;
private $_host = 'localhost';
private $_username = 'root';
private $_password = 'password';
private $_database = 'test';
public static function getInstance()
{
if (!self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
private function __construct()
{
try {
$this->_connection = new PDO("mysql:host=$this->_host;dbname=$this->_database", $this->_username, $this->_password);
echo 'Connected to database';
} catch (PDOException $e) {
echo $e->getMessage();
}
}
private function __clone()
{
}
public function getConnection()
{
return $this->_connection;
}
}
$db = Db::getInstance();