[英]How to disconnect or close database connection from DB in php mysql in OOPS
考慮 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=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();
}?>
另一件事是您可以創建構造函數和析構函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.