当我包含它时,我已经有一个连接到数据库的数据库文件
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
我通常通过以下方式访问它:
require( 'some-file-path' . 'class-database.php' );
$db = dbFactory::pdo();
问题如下:
如何从另一个类中访问 $db
?
例如,如果我有一个名为 class-html.php
的类文件并且在该类中(又名,作为类代码的一部分)我需要类似...:
class-html.php
class html {
...some code...
$db->query('SELECT * FROM tbl_head');
...some more code...
} //End: html
我一直在做但没有成功的是:
require( 'some-file-path' . 'class-database.php' );
$db = dbFactory::pdo();
require( 'some-file-path' . 'class-html.php' );
我收到错误消息,但不确定从这里开始做什么
最佳答案
您可以使用 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;
}
}
当您现在访问 dbFactory::getPDOinstance()
时,您将只有一个 PDO 实例,该实例使用 DB 在每个类中创建新实例
关于PHP:在类中使用数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20692415/