创建一个全局可访问的MySQLi对象 [英] Creating a globally accessible MySQLi object

查看:107
本文介绍了创建一个全局可访问的MySQLi对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个使用静态方法的类。这些函数使用

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();

}



根据我的理解,静态方法 DO NOT 使用__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.

推荐答案

这里有一种方法:

创建一个单例类,

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对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆