Q:

Connecting to database via constructor, close via destructor?

I have a question regarding database connection in PHP and MySQL. I wonder if it is possible to keep the database connection open, opening using a class and defining the connection in the constructor, then closing the connection again in the destructor.
I currently have a class which is an "html"-class, I have my website using this for it's layout and such. Would it pose any sort of (later on) problems, security risks or such if I would do as I earlier propose?
Regards,

A:

It's not uncommon to open a connection inside a constructor, and often then to store the connection resource in a property of the class.
You can explicitly close the database connection in the constructor, however it isn't usually necessary to do so since PHP will close the connection implicitly when it is no longer needed by the script.
class db {
  public $connection;

  public function __construct($params...) {
     $this->connection = mysql_connect(...);
     if (!$this->connection) {
        // throw an exception or set an error status...
     }
  }  
}

