I'm writing a program with multiple classes, most of which need to run a few database queries, and I have a single connection created as the program runs.

Whats the best way of allowing these classes to access the same database connection, which is created outside their scope. I'm currently using 'global $dbh' in the class methods which need it but would rather avoid thowing global variables around.

    Keep in mind that I'm not a super-star PHP programmer.
    That being said, I'd use a separate file for db connection and one for db configs (defining host, user, pass etc.):

    // ---------DBConnect.php ---------------
    include ('config.php');
    
    class DB {
    
      function connect() {
        mysql_connect('...') or die('...');
        // some more db-connection wise commands
      }
    
      // you could make the connection at object instantiation:
      function __constructor() {
        mysql_connect('...') or die('...');
        // some more db-connection wise commands
    
    // if you know you'll work with the same database, select it in here
    mysql_select_db('...');
      }
    
      function query($query) {
        mysql_query($query);
      }
    }
    
    $db = new DBConnect();

    And use this file all around:

    include DBConnect.php;
    
    // from hereafter I'll use $db, or $db->connect and $db->query

    You could use singletons also.

      the best trick is to make a single instance with a single pattern such as

      
      public static instance;
      
      public static function instance()
      {
         if(!self::$instance instanceof self)
         {
                self::$instance = new self();
         }
      
      return self::$instance;
      
       // now you have one access point threw and instance next you can ether extend each class witch is not recommended or you can build a simple registry that will call in each class as needed. //
      
      
        Write a Reply...