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

查看:28
本文介绍了创建一个全局可访问的 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();

}

据我所知,静态方法不要使用 __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 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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