2016-02-25 78 views
0

我有一個層類是這樣的:銷燬PDO連接?

class Database extends PDO 
{ 

public function __construct($connection) 
{ 
    parent::__construct(DB_TYPE . ":host=". $connection['host'] . 
     ";dbname=" . $connection['dbName'], $connection['username'], $connection['dbPass']); 
} 

我怎麼可以不設置在destruct連接?

回答

1

該連接在該PDO對象的生存期內保持活動狀態。若要關閉連接,您需要通過確保 所有剩餘的引用都被刪除來銷燬該對象 - 您可以通過將 NULL分配給保存該對象的變量來執行此操作。如果您不明確執行此操作,則PHP將自動關閉連接,當您的腳本結束時 。

http://php.net/manual/en/pdo.connections.php

請注意,如果初始化PDO對象作爲持久連接也不會自動關閉連接。

參考下面的例子用於使用類連接

class Db 
{ 
    # Class properties 
    private $DBH; // Database Handle 
    private $STH; // Statement Handle 

    # Func: __construct() 
    # Desc: Connects to DB 
    public function __construct() 
    { 
     // Connection information 
     $host = 'localhost'; 
     $dbname = 'removed'; 
     $user = 'removed'; 
     $pass = 'removed'; 

     // Attempt DB connection 
     try 
     { 
      $this->DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); 
      $this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
      echo 'Successfully connected to the database!'; 
     } 
     catch(PDOException $e) 
     { 
      echo $e->getMessage(); 
     } 
    } 

    # Func: query(sql statement) 
    # Desc: Sends a query to the DB 
    public function query($sql_statement) 
    { 
     $sql = array(':color' => $sql_statement); 
     $this->STH = $this->DBH->prepare("INSERT INTO color_table (color) value (:color)"); 
     $this->STH->execute($sql); 
    } 

    # Func: __destruct() 
    # Desc: Disconnects from the DB 
    public function __destruct() 
    { 
     // Disconnect from DB 
     $this->DBH = null; 
     echo 'Successfully disconnected from the database!'; 
    }