Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I already have a database file that connects to a database when I include it

class-database.php

class dbFactory {
    private static $host    = 'some.host.com';
    private static $name    = 'someDB';
    private static $user    = 'someUser';
    private static $pass    = 'somePassword';


    public function __construct() { }


    public static function pdo() {
        try {
            # MySQL with PDO_MYSQL
            return new PDO("mysql:host=$host;dbname=$name", $user, $pass);
            }
        catch(PDOException $e) {
            echo $e->getMessage();
            return null;
            exit;
            }  
    } // End: pdo()
} //End class

I usually access this by:

require( 'some-file-path' . 'class-database.php' );
$db = dbFactory::pdo();

Here is the question: How can I access $db from within another class?

For instance, if I have a class file called class-html.php and within that class (AKA, as part of the class code) I need something like...:

class-html.php

class html {
  ...some code...
  $db->query('SELECT * FROM tbl_head');
  ...some more code...
} //End: html

What I've been doing without success is:

require( 'some-file-path' . 'class-database.php' );
$db = dbFactory::pdo();

require( 'some-file-path' . 'class-html.php' );

I am getting error messages and am not sure what to do from here

share|improve this question
    
In this case, both answers are what I need to resolve my problem. However, this site does not allows to accept two entries as the answers. What should I to? –  Omar Dec 19 '13 at 23:19

2 Answers 2

You can use a Singleton class

class dbFactory {

    //...
    private static $pdo_instance = null;

    private static function getPDOinstance() {
        if (self::$pdo_instance === null) {
            try {
                self::$pdo_instance = new PDO("...");
            } catch (PDOException $e) {
                //...
            }
        }
        return self::$pdo_instance;
    }

}

When you now access dbFactory::getPDOinstance() you'll only have one PDO instance of creating new ones inside each class using the DB

share|improve this answer

Your class inside class-html.php can be modified a bit, along the following lines:

require( 'some-file-path' . 'class-database.php' );

class SomeClass {
  public $db;

  def __construct() {
    $db = dbFactory::getPDOinstance();
    // existing code ..
  }

  // other code      
}

Then, you can require the class as usual and:

require( 'some-file-path' . 'class-html.php' );
$obj = new SomeClass();
$obj->db->query('SELECT * FROM tbl_head')

UPDATE: This will create a new PDO instance if you instantiate SomeClass more than once.
UPDATE: Made use of kingkero's answer to use existing dbFactory instance, instead.

share|improve this answer
    
One may not want to create a new PDO object for every SomeClass object, nor for such objects to differ from those used elsewhere. –  eggyal Dec 19 '13 at 21:58
    
@stoic If an instance of a database initiated already, in this case $db, this "instance" cannot be accessed within another class (html) and that other class (html) has to create a whole new database instance? Am I correct? –  Omar Dec 19 '13 at 22:00
    
No, you can "save" the instance inside your dbFactory. You can read more about that in the wiki link I posted –  kingkero Dec 19 '13 at 22:01
    
@Omar: Yeah, if you have an active instance of $db, then it will be different than the one that the above solution creates for you, i.e. the database instance is created, again. If you prefer (and you should) to use a single instance of $db make dbFactory a singleton class, as kingkero has done in his answer, and then use my method to call the appropriate behaviour. I will update my answer to build upon kingkero's answer. –  Stoic Dec 19 '13 at 22:03
    
@stoic Does it matters that SomeCalss's $db is public? Can it be private or protected or it really does not matters? –  Omar Dec 19 '13 at 23:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.