Passing $db object to other classes so they can access the database Passing $db object to other classes so they can access the database database database

Passing $db object to other classes so they can access the database


There is a difference, but it's not really the difference you may think.

In PHP5, "$db" holding an object is basically equivalent to a "Foo *" in C or C++. In other words, $db doesn't store the whole object, it just stores a small token that lets the code find the object when necessary. When you pass this token by value, it's as fast as passing an integer value rather than a copy of the entire object. But if you assign $db, it doesn't change the value in the caller because you're changing your local variable holding the token to contain a different token.

If the function takes "&$db", that's basically the equivalent of passing "Foo **" in C, or more correctly a function taking a "Foo *&" in C++. The call is just as fast since it's the same size thing that's being passed, but inside the function if you assign to $db it will change the value of $db in the caller because the "pass by reference" variable points you to the memory location holding the token in the caller.

The best way to do it is to pass by value (do not use "&") unless you know what you're doing and why you're doing it.


That's a good question.

You can always do a test by opening a $db handle, passing it to a function, and checking them via the === operator to make sure they are the same object.


This would be a good job for static methods. That is how many frameworks accomplish the same task.

class DB{   private static $db = FALSE:   public static function init($dbConfig)   {      if(! self:$db)      {         self::$db = new Database($dbConfig);      }   }   public static function preparedSelect($sql, $params)   {      if(! self::$db)      {         die("call the init method first");      }      // db stuff, where you would call $this->db call self::$db   }}

So in your other classes where you want to make calls to the database all you would have to do is:

class General{   public function __construct()   {      DB::init($dbConfig);   }   public function someMethod()   {      $params = array('username' => $username);      $result = DB::preparedSelect('select password, salt from users where username = :username', $params);   }}