【发布时间】:2015-10-16 02:45:53
【问题描述】:
我有以下数据库类。我的想法是,这将检查该类的现有实例并返回它,而不是创建一个新的数据库连接。
当我运行代码时,它会创建一个连接。当我刷新页面时,会创建另一个连接(检查 MySQL 连接)。
我的想法不正确吗?对使用 OOP 还很陌生,对于新手问题,我们深表歉意!
任何正确方向的帮助或指示将不胜感激。
非常感谢。
<?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();
【问题讨论】: