Global Variable - database connection?

前端 未结 1 1255
清酒与你
清酒与你 2021-01-05 01:20

I am trying to connect to a database (MySQLi) just once, but am having problems doing so.

How do I make a connection global for the entire script? There are multiple

相关标签:
1条回答
  • 2021-01-05 01:45

    Personally, I use a singleton class. Something like this:

    <?php
    
    class Database {
    
        private static $db;
        private $connection;
    
        private function __construct() {
            $this->connection = new MySQLi(/* credentials */);
        }
    
        function __destruct() {
            $this->connection->close();
        }
    
        public static function getConnection() {
            if (self::$db == null) {
                self::$db = new Database();
            }
            return self::$db->connection;
        }
    }
    
    ?>
    

    Then just use $db = Database::getConnection(); wherever I need it.

    0 讨论(0)
提交回复
热议问题