Reputation: 1105
I have a layer class like this:
class Database extends PDO
{
public function __construct($connection)
{
parent::__construct(DB_TYPE . ":host=". $connection['host'] .
";dbname=" . $connection['dbName'], $connection['username'], $connection['dbPass']);
}
how I can unset the connection in the destruct
?
Upvotes: 1
Views: 2449
Reputation: 2530
The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
http://php.net/manual/en/pdo.connections.php
Note that if you initialise the PDO object as a persistent connection it will not automatically close the connection.
Refer the example below for using connection in classes
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!';
}
Upvotes: 3