在OOPS中如何在php mysql中断开或关闭数据库与数据库的连接

在OOPS中如何在php mysql中断开或关闭数据库与数据库的连接,php,mysql,database,oop,Php,Mysql,Database,Oop,考虑3个类DBCONNECT,book,new class dbconnect { protected $db_conn; public $db_user='xxxx'; public $db_pass='xxxx'; public $db_host='localhost'; public $db_name='xxxx'; function connect() { try{ $this->db_conn=ne

考虑3个类DBCONNECTbooknew

class dbconnect {
    protected $db_conn;
    public $db_user='xxxx';
    public $db_pass='xxxx';
    public $db_host='localhost';
    public $db_name='xxxx';

function connect() {
        try{
            $this->db_conn=new PDO("mysql:host=$this->db_host;dbname=$this->db_name",$this->db_user,$this->db_pass);
            return $this->db_conn;
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }
}


include_once ( 'class.dbconn.php' );

class Book{
    public $link;

    public function __construct(){
        $db_conn=new dbconnect();
        $this->link = $db_conn->connect();
        return $this->link;
    }
}

class new{
include_once 'classes/class.book.php';
$book = new Book();
}

一切正常我的代码中没有错误,但我怀疑是否会关闭与数据库的连接。是否必须关闭连接?如果是强制性的,那么如何关闭连接以及需要在哪个类中编写代码?

手动关闭连接不是强制性的。PHP将自己处理这个问题。如果要手动关闭它,可以使用
$this->db_conn=null

public function disconnect() {
    $this->db_conn = null
}
如果你想成为一个完美主义者,你也可以这样做,尽管这不是必须的

public function __destruct() {
    $this->disconnect();
}
你的新代码

<?php
class dbconnect {
    protected $db_conn;
    public $db_user='xxxx';
    public $db_pass='xxxx';
    public $db_host='localhost';
    public $db_name='xxxx';

function connect() {
        try{
            $this->db_conn=new PDO("mysql:host=$this->db_host;dbname=$this->db_name",$this->db_user,$this->db_pass);
            return $this->db_conn;
        }
        catch (Exception $e){
            return $e->getMessage();
        }
    }

function disconnect()
    {
            try
            {
                $this->db_conn=null;
                return $this->db_conn;
            }
            catch (Exception $e){
                return $e->getMessage();
            }
            }
    }
}


include_once ( 'class.dbconn.php' );

class Book{
    public $link;

    public function __construct(){
        $db_conn=new dbconnect();
        $this->link = $db_conn->connect();
        return $this->link;
    }
}

class new{
include_once 'classes/class.book.php';
$book = new Book();

$close = new dbconnect();
// this will close connection
$close->disconnect();


}?>


还有一件事是可以创建构造函数和析构函数

包含数据库连接的数据库类。我假设您正在使用自己的数据库类,因为您使用的是dbconnect类,虽然如果您要管理一个或两个连接,通常不需要,但是如果您要有很多连接,则需要在不需要时手动关闭它们。当然,最好的做法是总是关闭一个不再使用的连接。然后我希望添加休闲代码公共函数uu destruct(){$this->db_conn=null;}