下面是数据库连接的代码。,下面还有更多的方法。
为了保持简单,我决定为其他方法创建一个单独的类。所以,无论如何,我可以连接到数据库时实例化其他类。
Db.php
class Db{
private static $_instance = null;
private $_db;
private function __construct(){
try{
$this->_db = new PDO('mysql:host = localhost;dbname=db_xoo', 'root', '');
}
catch(PDOException $e){
die($e->getMessage());
}
}
public static function get_instance(){
if(!isset(self::$_instance)){
return self::$_instance = new Db();
}
else{
return self::$_instance;
}
}
Other.php
<?php
class Other{
.
.
.
public function blah(){
database queries..
}
.
.
}
?>
现在当我实例化类other。我应该在other.php
中添加什么,以便它可以自动连接到数据库,而不是在创建$test = new Other()
之前每次都调用Db::get_instance()
使用其他类
这样的class Other{
private $_db;
private function __construct(){
$this->_db = Db::get_instance();
}
public function blah(){
database queries.. $this->_db->query()
}
.
.
}