Reputation: 12287
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
Upvotes: 1
Views: 210
Reputation: 10754
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.
Upvotes: 1
Reputation: 10638
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
Upvotes: 2