php - 每次我需要一些东西时创建新的mysql连接对象

标签 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();
    }

    [...]
}

这段代码工作得很好,但有一件事困扰着我。我想知道每次调用 start_connection() 时是否真的需要创建一个新的连接对象 new mysqli()。有类似重新连接之类的东西吗?

最佳答案

您可以在数据库类中存储 mysqli 实例,并在“私有(private)函数数据库”函数中声明它(如果您愿意,可以通过调用 $this->start_connection() 来声明)

如果您愿意,您也可以提供一个静态函数来关闭连接。

关于php - 每次我需要一些东西时创建新的mysql连接对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31343325/

相关文章:

php - 使用 $.ajax 引入多个字段值

php - 如何在 PHP 中设置自定义 header

php - 如果键相同,如何将值附加到数组中

mysql - 如何在MySQL中引用SELECT语句结果表?

mysql/sql : how to delete all rows except the Nth last per user?

java - oop 中的多态性

php,如何简化一个php脚本?

c# - 什么样的访问修饰符可以应用于类?

java - 树遍历不打印所需的解决方案

php - 使用 preg_replace 修改文件链接