PHP:在类中使用数据库
I already have a database file that connects to a database when I include it
我已经有一个数据库文件,当我包含它时,它会连接到数据库
class-database.php
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?
问题是:如何从另一个类中访问$db ?
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的类文件。在这个类(也就是类代码的一部分)中,我需要类似…
class-html.php
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
我收到错误消息,不知道从这里做什么
2 个解决方案
#1
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
当您现在访问dbFactory: getPDOinstance()时,您将只有一个PDO实例,使用DB在每个类中创建新的PDO实例
更多相关文章
- PHP实例————万年历
- PHP文件锁同步实例
- PHP中使用sleep函数实现定时任务实例分享
- 040-PHP使用闭包函数来进行父实例的变量自增,正确示例
- 实例讲解:.NET如何访问MySQL数据库
- 亚马逊AWS EC2云实例AMI安装LNMP环境(3)——Mysql5.5
- MySQL编译安装(多实例)
- MySQL“在建立到SQL Server的连接时发生与网络相关或特定于实例
- 将jQuery datepicker应用到多个实例