DataBase Connection Class, Maintain Static Connection Variable??

Posted on 2004-11-15
Last Modified: 2008-01-09
Hello, I had this problem in PHP 4 and Squinky offered a solution with globals, but now that I'm using PHP 5 I'd like to implement a solution with a static class variable, but I'm not sure how.  Here is the original question I posted, with an addition at the bottom:

****old question**********************************************************

I have several data classes that all extend a parent "DBObject" class.

The "Connect_DB()" function is in the DBObject class, and all the children inherit it.  However, I need a way to only allow ONE db Connection through the DBObject class, no matter how many times it is called by the children.

The specific problem is that class Company has a member variable, which is a type of class Collection.  Now, both Company and Collection extend DBObject, so what inevitably ends up happening, is that Company creates a new DBObject, and SO DOES Collection.  Then there are 2 DBConnections.

How can I maintain a global static DBOjbect that all the children can use, but not accidently create a second instance, or override the first connection?

If the entire OO design I have sounds funny, your critique in that regard is welcome as well.


I don't mind new connections being created by different objects in the system i.e.  if you navigate to the 'viewUser.php' page, the UserCollection class would create it's own connection to the DB.  If you then navigated to the 'viewProject.php' page, the ProjectCollection class would create a NEW connection to the DB...I don't want to persist the DB connection one time per session or anything like that.

Here is the problem:
ProjectCollection has a delete() method...which is basically this:
foreach(ProjectCollection as $objProject)

In this case, I'd like each of the $objProject objects inside the collection to use the ONE DB connection that ProjectCollection would have initialized when the page loaded.  I could probably pass a flag to each of my object's delete methods telling the child not to connect to the database itself, but I'm looking for a more elegant OO solution, where the children 'KNOW' that they are inside a collection and don't need to connect each time one of a hundred objects gets deleted by the collection object itself.

Thanks for your insights.


ps, again, if you have alternative OO design solutions that you'd like to add, I'd love to hear them.
Question by:kbach
    LVL 48

    Accepted Solution

    Just a pratical note. If you use mysql and connect in one script to the same host with the same user and password, a new connection is only made to the db-server is you set the 4th parameter to true.

    The Typical OO design is that your object use a DB-Object and do not inherit from that object.
    class DBObject {
     function delete($table, $condition){
         //generate SQL and execute sql

      function &sigleton() {
        static $dbObj = null;
        if (is_null($dbObj)) {
            $dbObj = new DBObject();
            // settings taken from a include, ..
            $dbObj->setConnection($host, $user, $passw);
        return $dbObj;

    class Collelction{
        var $_db;
        function Collection() {
            $this->_db = DBObject::singelton();
        function delete() {
           $this->_db->delete('MyTable', "Id=" . $this->ID);

    So you have only one DB-Object with one connection. And its still OO.
    Just my 2 cents
    LVL 1

    Author Comment


    Question: did you use a static $dbObj variable inside the function singleton() out of habit because PHP 4 didn't support static class variables?  In other words, in PHP 5 could I avoid the need for the singleton function altogether by declaring a static class variable and having that returned by a getLink() function?

    LVL 1

    Author Comment

    I didn't realize that mysql used the same link unless you explicitly tell it to create a new connection.  This means that my original code was working the way I wanted it, which is one connection per script execution.

    I like your idea of the singleton method, but I'd like to keep the DataObject class as a parent class for all my dataObject subclasses, as they are just that, DB objects and are never used for anything except CRUD methods.

    This way, I can always have a reference to $this->dbConnection no matter how many levels deep in the hierarchy I go.  With an external DB class that is a composite of each of my data classes, I'd have to explicity get a link when I need it by going to the singleton function.

    What I DO like about the singleton though is that it EXPLICITLY forces the db connection only once, and doesn't defer responsiblity to mysql itself.  Again though, I'd like protected access to the $link returned by the static method, without having to call the singleton each time.

    I tried to emulate the same functionality by declaring a static CLASS variable, and checking if that was null inside my Connect() routine, which would do what the singleton does, BUT give all children access to $this->link without having to return a link each time.

    I didn't have any success though, so seeing as I'm just wasting time, I'll leave my original code in there, and defer to mysql to handle whether it's a new connection or not.

    In the future though, if anyone has code for me to declare a static class $_db object instead of the static function variable, that would allow me access to it through all levels without recalling the singleton function when I want the reference.

    Thanks hernst42, I'm learning more every day :-).
    LVL 1

    Author Comment

    hernst42, or anyone else:

    Do you know if the mysql_connect() rule mentioned above (use the same link if called twice in same script) applies to the new mysqli_connect() function recently added?  I need to change my code to use this newer c api as I'm using stored procedures now in Mysql 5 and need extra params...

    Just a question.
    LVL 48

    Expert Comment

    as far I can see the mysqli_connect will make a new connection every time. So you should use a DB-Object instead of inherit from the DB-class.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    This is a general how to create your own custom plugin system for your PHP application that you designed (or wish to extend a third party program to have plugin functionality that doesn't have it yet).  This is not how to make plugins for existing s…
    Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
    The viewer will learn how to dynamically set the form action using jQuery.
    This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now