How to use singleton as connection in php class

匆匆过客 提交于 2019-12-13 04:38:29

问题


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;
  }
}

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
    }

}

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


回答1:


It should be

    $this->result = mysqli_query($this->dbc->dbc, $q);
                                            ^^^^----

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.



来源:https://stackoverflow.com/questions/19302072/how-to-use-singleton-as-connection-in-php-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!