OOP使用其他类的数据库连接
问题描述:
下面是数据库连接的代码。 &下面有更多的方法。
为了保持简单,我决定为其他方法创建一个单独的类。所以无论如何,我可以在实例化其他类时连接到数据库。
db.php中OOP使用其他类的数据库连接
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.What应other.php
所以加,它可以对数据库,而不是自动连接在创建之前每次调用Db::get_instance()
$test = new Other()
答
use cons道在其他类
这样
class Other{
private $_db;
private function __construct(){
$this->_db = Db::get_instance();
}
public function blah(){
database queries.. $this->_db->query()
}
.
.
}
好了,但如果我想在other.php使用静态方法。它如何连接到数据库? –
使用'$ _db'连接到其他类的数据库 – ashkufaraz