問題描述
我有多個使用靜態方法的類.這些函數使用
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 是在全局可訪問文件中定義的數據庫變量.最近,我的網站開始變慢,在分析腳本后,我意識到創建對象 ($mysqli) 的調用導致了這個問題.
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.
我的大部分類都從 mysqli 擴展,使得
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();
}
據我所知,靜態方法不要使用 __construct 方法.
It is to my understanding that static methods DO NOT use the __construct method.
有人可以指導我如何創建 $mysqli 對象,以便所有需要它的靜態方法都可以訪問它.
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.
推薦答案
這是一種方法:
創建一個可以從任何地方靜態訪問的單例類.
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 ;
}
}
一個例子是:
$mysqli = DBConnector::getInstance() ;
但是我建議也使用另一種解決方案:
$mysqli = new MySQLi(a,b,c,d) ;
然后你可以將該對象傳遞給其他類(構造函數)
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) ;
這篇關于創建一個全局可訪問的 MySQLi 對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!