破坏PDO连接?

时间:2016-02-25 11:49:18

标签: php

我有一个这样的图层类:

class Database extends PDO
{

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

如何取消destruct中的连接?

1 个答案:

答案 0 :(得分:2)

  

该连接在该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!';
    }