2

I'm working on a project for school (Deadline in June; plenty of time given ^^).

At the moment there is a database in the conf.php (every other .php includes this one; it has a variable which references a mysqli-object) and i am accessing the database in every method of a classs via "global $db_conn;". The problem is, if I open just the class.php, it doesn't include the conf.php and it throws errors. So I thought about adding an private instance/static variable for the mysqli-Object with EVERY object. This is not working (unexpected T_NEW):

class foo{
    private static $db_conn = new mysqli("", "", "", "");
}

How do you handle db-connections? How would you handle this specific problem?

Thanks in advance ^^

2 Answers2

0

you could use include_once the conf.php file in both your other files and the class file. that way you always have the contents (and db reference).

Nick Andriopoulos
  • 10,313
  • 6
  • 32
  • 56
  • thanks for your answer. the problem is that all the class and the conf.php are in different folders and sub-folders. So i can't use the include_once or require_once. but i'll restructure my project, so that all the import stuff is in the same folder, that should fix my problem. Thank you –  Mar 08 '13 at 15:37
-1

If you make your db connection a Singleton class and you have an __autoload() function, then you can just have a dbconnection property in each of your classes which is set during construction.

e.g.

class DBConnection{

  private static $instance;

  private function __construct(){
    //make your db connnection
  }

  public static function get_connection(){
    if(empty self::$instance) self::$instance = new DBConnection;
    return self::$instance;
  }
}

class Foo {

  private $db;

  function __construct(){
    $this->db=DBConnection::get_connection();
  }
}
dnagirl
  • 20,196
  • 13
  • 80
  • 123
  • Thank you. That's a great idea. I think i will give it a try. ^^ Thank you –  Mar 08 '13 at 15:40
  • @Mathlight, the short answer is: because it introduces global state in the application. It's basically the same as using global variable. All the same penalties apply. To see a much better approach, check [here](http://stackoverflow.com/a/11369679/727208) though, you will nee to understand how anonymous function work. – tereško May 12 '14 at 08:11
  • @tereško, thanks for the link. I'm watching the Google video now, very interesting – Mathlight May 12 '14 at 08:24