Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP父类是一个DB连接:由于继承而多次使用会影响性能吗?_Php - Fatal编程技术网

PHP父类是一个DB连接:由于继承而多次使用会影响性能吗?

PHP父类是一个DB连接:由于继承而多次使用会影响性能吗?,php,Php,我有一个处理连接的类: Class db_connect{ private $server; private $username; private $password; private $database; protected function Connect(){ $this->server = "localhost"; $this->username = "root"; $this->

我有一个处理连接的类:

Class db_connect{

    private $server;
    private $username;
    private $password;
    private $database;

    protected function Connect(){
        $this->server = "localhost";
        $this->username = "root";
        $this->password = "";
        $this->database = "db_test";

        $conn = new mysqli($this->server, $this->username, $this->password, $this->database);
        return $conn;
    }
}
如果我有几个扩展到此父类的子类,由于它总是多次尝试连接,它会以某种方式影响性能吗?
如果是这样的话,我该如何改进呢?谢谢。

每次调用该方法时,您都可以进行连接。不过,让我们重写一下:

Class db_connect{

    private $server;
    private $username;
    private $password;
    private $database;
    private static $connection;

    protected function Connect() {      
        if(!(static::$connection instanceof mysqli)) {
            $this->server = "localhost";
            $this->username = "root";
            $this->password = "";
            $this->database = "db_test";

            static::$connection = new mysqli($this->server, $this->username, $this->password, $this->database);
        }

        return static::$connection;
    }
}

在上面的例子中,只有一个连接。这就是为什么它被定义为
static
。现在您可以调用
$obj->Connect()只要您愿意,它将只使用一个连接。其他人提到了它,它被称为单身。它有缺点和优点,但这超出了您的问题范围。

我宁愿使用
setDatabaseConnection(db\u connect$dbConnection)
并进行设置,这样您就只有一个实例/连接了实用示例::数据库类的一部分,如果您不需要在运行时始终更改连接,那么最终将创建多个连接。如果将其乘以多个用户,很快就会超过MySQL连接limit@golddragon007谢谢你提供这些有用的信息。你说得对。@ManuelMannhardt谢谢你,我也要试试:)嗨,Mjh,非常感谢!我本来打算学习这个单例的东西,但它让我大吃一惊,幸运的是你已经为我写了它:)我有一个问题,我使用了你的代码,我用一个名为my_class的子类测试了它,使用了一个名为my_method的方法,我调用了my_method,但随后发生了一个错误:致命错误:未捕获错误:无法访问属性my_class:$connection。这意味着什么?没关系。我解决了这个问题。我刚刚将私有静态$connection更改为protected。再次感谢您的帮助:)@AdrianCelis没问题,我很高兴您解决了问题,祝php好运!:)