Creating a globally accessible MySQLi object

前端 未结 3 1159
清歌不尽
清歌不尽 2021-01-04 09:40

I have multiple classes that use static methods. These functions connect to the database using

$mysqli = new mysqli(DB_SERVER, DB_USER, DB_P         


        
3条回答
  •  囚心锁ツ
    2021-01-04 10:26

    Here is one approach:

    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 ;
        }
    }
    

    An example would be:

    $mysqli = DBConnector::getInstance() ;
    

    Hovewer I suggest using another solution as well:

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

提交回复
热议问题