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

3
  • 1
    You have a double equals on this line: $this->dbc==DatabaseConnection::connectDb(); Commented Oct 10, 2013 at 17:16
  • I'm sorry i miss typed my question , corrected! Commented Oct 10, 2013 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 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). Commented Oct 10, 2013 at 21:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Here's the barebones version of a singleton in PHP: stackoverflow.com/questions/8954304/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.