問(wèn)題描述
我有多個(gè)使用靜態(tài)方法的類(lèi).這些函數(shù)使用
I have multiple classes that use static methods. These functions connect to the database using
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
其中常量 DB_SERVER、DB_USER、DB_PASS、DB_NAME 是在全局可訪問(wèn)文件中定義的數(shù)據(jù)庫(kù)變量.最近,我的網(wǎng)站開(kāi)始變慢,在分析腳本后,我意識(shí)到創(chuàng)建對(duì)象 ($mysqli) 的調(diào)用導(dǎo)致了這個(gè)問(wèn)題.
where the constants DB_SERVER, DB_USER, DB_PASS, DB_NAME are database variables defined in a globally accessible file. Recently, my site started becoming slow and after profiling the script I realized that the call to create the object($mysqli) was causing this problem.
我的大部分類(lèi)都從 mysqli 擴(kuò)展,使得
Most of my classes extend from mysqli such that
public function __construct($user_id) {
parent::__construct(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
$this->retrieve_user_details($user_id);
$this->check_user_account_type();
}
據(jù)我所知,靜態(tài)方法不要使用 __construct 方法.
It is to my understanding that static methods DO NOT use the __construct method.
有人可以指導(dǎo)我如何創(chuàng)建 $mysqli 對(duì)象,以便所有需要它的靜態(tài)方法都可以訪問(wèn)它.
Could someone guide me on how I can create the $mysqli object once such that it can be accessed by all static methods that require it.
推薦答案
這是一種方法:
創(chuàng)建一個(gè)可以從任何地方靜態(tài)訪問(wèn)的單例類(lèi).
Create a singleton class, that can be accessed statically from anywhere.
class DBConnector {
private static $instance ;
public function __construct($host, $user, $password, $db){
if (self::$instance){
exit("Instance on DBConnection already exists.") ;
}
}
public static function getInstance(){
if (!self::$instance){
self::$instance = new DBConnector(a,b,c,d) ;
}
return $instance ;
}
}
一個(gè)例子是:
$mysqli = DBConnector::getInstance() ;
但是我建議也使用另一種解決方案:
$mysqli = new MySQLi(a,b,c,d) ;
然后你可以將該對(duì)象傳遞給其他類(lèi)(構(gòu)造函數(shù))
Then you could pass that object to other classes (constructor)
class Shop {
private $mysqli ;
public function __construct(MySQLi $mysqli){
$this->mysqli = $mysqli ;
}
}
$show = new Shop($mysqli) ;
這篇關(guān)于創(chuàng)建一個(gè)全局可訪問(wèn)的 MySQLi 對(duì)象的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!