每次我需要的时候创建新的mysql连接对象

时间:2015-07-10 14:27:37

标签: php mysql oop

我在PHP发现了新的事情并且我正在尝试执行这项简单任务:从MySql数据库获取数据。

我创建了一个单例类来与数据库进行通信:

class Database {
    private static $db = null;
    private $servername;
    private $username;
    private $password;
    private $connection;

    private function Database(){
        $this->servername = "localhost"; 
        $this->username = "user";
        $this->password = "123456";
    }

    public static function get_database(){
        if(!static::$db){
            static::$db = new Database();
        }
        return static::$db;
    }

    function start_connection(){
        $this->connection = new mysqli($this->servername, 
                                       $this->username, 
                                       $this->password);
    }

    function execute_query($query){
        $this->start_connection();

        [...]

        $this->disconnect();
    }

    function disconnect(){
        $this->connection->close();
    }

    [...]
}

这段代码运作得很完美,但有一件事让我感到烦恼。每次拨打new mysqli()时,我都想知道是否真的需要创建新的连接对象start_connection()。有什么像reconnect

1 个答案:

答案 0 :(得分:0)

您可以在Database类中存储mysqli实例,并在"私有函数数据库"中声明它。功能(如果你愿意,可以通过调用$ this-> start_connection())

如果您愿意,也可以提供静态功能来关闭连接。

相关问题