如何使用singleton作为php类中的连接 [英] How to use singleton as connection in php class
问题描述
我是新的OOP php,现在我试图了解的整体模式,但我在某处共享所有类的数据库连接。 我指的是 answer ,它使db连接成为单例类,并在每个构造函数中调用它。
I am new to OOP php , now i trying to understand the overall pattern but i struck somewhere at sharing database connection for all classes. I am referring to this answer which make db connection a singleton class and call it at each constructor.
这是单例数据库类,应该做连接部分,我有我的自动载入集
This is the singleton database class , should do the connect part and i have my autoload set
class DatabaseConnection{
private static $instance;
private $dbc;
private function __construct(){
$this->dbc = mysqli_connect(...);
}
public static function connectDb(){
if(empty(self::$instance)){
self::$instance = new DatabaseConnection;
}
return self::$instance;
}
}
这是我的类,我试图连接db构造函数
This is my class , i tried to connect db in the constructor
class SlideShow {
private $dbc;
private $result;
function __construct() {
$this->dbc=DatabaseConnection::connectDb();
$this->result=$this->getSlideShow();
}
private function getSlideShow(){
$q = "SELECT * FROM table";
$this->result = mysqli_query($this->dbc, $q);
//the error stated $dbc , object given
}
}
我在SlideShow类有一个问题,说 $ dbc是object',我的问题是我做对吗?如果是,我如何解决这些问题,我很难理解 answer 已发布
I am having a problem in my SlideShow class which saying the $dbc is object' , my question is am i doing it right ? If yes , how do i fix the stuff , i had a hard time to understand the answer posted
推荐答案
应该是
$this->result = mysqli_query($this->dbc->dbc, $q);
^^^^----
注意对象引用中的双重dbc。第一个是在 Slideshow
类中的私有 dbc
属性,第二个dbc是在您的DB类。
Note the doubled dbc in the object reference. First one is the private dbc
attribute in your Slideshow
class, the second dbc is the actual DB handle that's created in your DB class.
这篇关于如何使用singleton作为php类中的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!