DataBase Connection Class, Maintain Static Connection Variable??

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.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
kbachAuthor Commented:

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?

kbachAuthor Commented:
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 :-).
kbachAuthor Commented:
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.
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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.