0

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

Community
  • 1
  • 1
Leon Armstrong
  • 1,285
  • 3
  • 16
  • 41
  • 1
    You have a double equals on this line: `$this->dbc==DatabaseConnection::connectDb();` – Jimbali Oct 10 '13 at 17:16
  • I'm sorry i miss typed my question , corrected! – Leon Armstrong Oct 10 '13 at 17:19
  • 1
    **Don't use singletons.** Ever. It is an antipattern, which create a global state in your applications. Instead you should learn about dependency injection and how to implement it in your code. [This](http://stackoverflow.com/a/11369679/727208) post might give you some pointers (of course, you would have to alter for use with MySQLi instead of PDO, but that is an insignificant detail). – tereško Oct 10 '13 at 21:53

1 Answers1

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.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Alright I found it , and I need to change the private $dbc to public $dbc , and last question ... Did i achieve the pattern mentioned in that answer i referring to? – Leon Armstrong Oct 10 '13 at 17:36
  • Here's the barebones version of a singleton in PHP: http://stackoverflow.com/questions/8954304/abstract-singleton-pattern-class?rq=1 – Marc B Oct 10 '13 at 17:37