My Database Class in PHP is shown below. Is it considered a best practice to have a destruct function?
<?php
class Database{
private $host;
private $username;
private $password;
private $database;
private $conn;
public function __construct($host, $username, $password, $database){
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->connect();
}
public function connect(){
try{
$this->conn = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database, $this->username, $this->password);
} catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
public function runSQL($query, $params=null){
try {
$statement = $this->conn->prepare($query);
$statement->execute($params);
return true;
} catch (PDOException $e) {
print "Error" . $e->getMessage();
}
}
public function close(){
$this->conn = null;
}
/*
// is this needed??
function __destruct() {
$this->conn->close();
}
*/
}
?>
My concerns for not needing- and therefore I have excluded it from my scripts- are:
Wouldn't the database connection be closed anyways after the script is run?
If I have several calls to the database in a single script, would closing the connection on one interfere with subsequent calls? Example below:
$db = new Database( [configuration here]);
function one($db) {
$sql = " ...";
return $db->runSQL($sql;
}
function two($db) {
$sql = " ...";
return $db->runSQL($sql);
}
// this should be fine
$x = one($db);
// if the destruct is in place,
// wouldn't I get an error here?
$y = two($db);
Everything works fine without the destruct being included, but I'm concerned if this is susceptible to memory leaks.
Thank you in advance :)