I created a class for database connection and query called "DBConnection". Now I created other classes such as "Products" and "Customers", each of which require an instance of the DBconnection object. Is it a good idea to create an instance of DBConnection in each of these classes? If not, is it better to set $dbconn as global variable, or instead pass this object in each of other classes in thier respective constructors? Thanks, Amit
Are these all independent classes or are they methods of the same class? Is either class a child of the other one? If they are methods of the same class, or are extending or parent-child related, I would instantiate the db connection in __construct(), and close the connection in __destruct(). This will make sure it gets opened and closed properly, and will automatically be usable by any method in the class, or it's child. Also, if you use the singleton design pattern for the db class, you wont have to worry about opening multiple connections to the db. Here's a few tutorials on using a singleton for the db class if you're not already using it. http://www.plentyofcode.com/2007/11/mysql-singleton-class-with-php5.html http://www.tonymarston.net/php-mysql/singleton.html http://dev.thatspoppycock.com/index...base_Class_Using_the_Singleton_Design_Pattern
I always try to use /global/ vars ( public $con, $db ) .. it's just easier when you don't need to think about destructors or access levels.
Yep the singleton seems to be the way to go these days. But I guess you could just make an instance and then pass it around instead.
You only want one instance of the dbconnect class so a singelton is the way to go. If you realize that you're going to need more than one or two singletons for other global data/resouces (like a config object for example) you'll want to go with some sort of registry.
er, you could also write the other classes so they extend the db class so they can inherit the methods you want.