开发者

Access database variable in functions with PHP

开发者 https://www.devze.com 2022-12-21 16:44 出处:网络
I am fairly new to PHP and I have found that a lot of my开发者_如何转开发 functions require access to the database. The problem is I currently connect to the database in a file that I require at the t

I am fairly new to PHP and I have found that a lot of my开发者_如何转开发 functions require access to the database. The problem is I currently connect to the database in a file that I require at the top of every page like so:

$db = new mysqli("localhost", "my_user", "my_password", "world");

The problem I find is then when I want to access it within a function I have to pass the $db variable to it... which works fine, but is there an easier way?


The easiest (but not the best) way is to add 'global' keyword in each function. Example:

$db = new mysqli("localhost", "my_user", "my_password", "world");
function foo() {
  global $db;
  $db->query(....
}

Much better way is to create your own class My_DB and define it as singleton. Then you will be able to call db object as an instance of the My_DB.

class My_DB {
  protected $_db = null;

  protected static $instance = null;

  protected function __construct() {
    $this->_db = new mysqli("localhost", "my_user", "my_password", "world");
  }

  public static function getInstance() {
    if (empty(self::$_instance)) {
      self::$_instance = new self();
    }
    return self::$_instance;
  }
}

And then anywhere in your code you can do the following:

function foo() {
  $db = My_DB::getInstance();
  $db->query(....
}


You can call them as functions on the $db object, e.g. $db->query(...).


Take a look at doctrine. There is a little bit of ramp up but it is very nice.

Otherwise put that code in an include file and include "db.php"; in your pages. Preferable you have 1 include file that gets you everything you need for your site, and you add the $db code there.

If you really want to be quick and dirty, make $db a global and then you can access it anywhere. This isn't great coding practice.

0

精彩评论

暂无评论...
验证码 换一张
取 消