我对PHP非常熟悉,但我刚开始用它做一些面向对象的东西。我想建立一个单例数据库连接,但我遇到了一个问题和错误。“致命错误:允许的内存大小为134217728字节耗尽(试图分配523800字节)” 我知道我运行的查询不应该耗尽内存
$con = getConnection();
$stmt = $con->prepare("SELECT gene_name,jgi_protein_id FROM jgi_transcriptid_proteinid_match where our_protein_id = ?");
以下是该课程的代码。
class Connection
{
// Store the single instance of connection
private static $connection;
private function __construct()
{
$connection = new mysqli(HOSTNAME, DBUSER, PASSWORD, DBNAME);
if ($connection->connect_errno)
die("Failed to connect to MySQL: (" . $connection->connect_errno . ") " . $connection->connect_error);
}
public static function getInstance()
{
if (!self::$connection)
self::$connection = new Connection();
return self::$connection;
}
public function prepare($query)
{
$statement = $this->prepare($query);
return $statement;
}
}
我正在使用mysqli作为数据库的东西。
答案 0 :(得分:5)
此代码中存在几个问题:
无限递归
public function prepare($query)
{
$statement = $this->prepare($query);
return $statement;
}
引用局部变量,而不是静态变量
代码可能应该引用self::$connection
。但是,基于课程,我不确定,self::$connection
在getInstance()
中以不同的方式使用,我看不到任何地方。
private function __construct()
{
$connection = new mysqli(HOSTNAME, DBUSER, PASSWORD, DBNAME);
if ($connection->connect_errno)
die("Failed to connect to MySQL: (" . $connection->connect_errno . ") " . $connection->connect_error);
}
命名混淆
该类称为Connection
,它包含一个名为$connection
的静态变量,它存储该类的单例实例。构造函数包含另一个$connection
,而不是 mysqli 连接。
重构类 - 未完成修复
下面的课程尚未经过测试,仅供参考。使用风险自负。
class Connection { //存储类的单个实例 private static $ instance; //存储mysqli连接 私人$连接;
public function __construct() {
// NOTE: it would be better to pass connection parameters as arguments
$this->connection = new mysqli(HOSTNAME, DBUSER, PASSWORD, DBNAME);
if ($this->connection->connect_errno)
die("Failed to connect to MySQL: (" . $this->connection->connect_errno . ") " . $this->connection->connect_error);
}
public static function getInstance() {
if(empty(self::$instance)) {
self::$instance = new Connection();
}
return self::$instance;
}
public function prepare($query) {
$statement = $this->connection->prepare($query);
return $statement;
}
}