How to use singleton as connection in php class

2019-09-06 19:13发布

问题:

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.