I recently began restructuring some of my "copy-paste" database classes I use for projects. I was working over the login class and came across an interesting function.
My Login class has a function that looks like this:
function &db_connect() {
require_once('mysql.php');
$db = new DB();
return $db;
}
What's interesting is it returns a reference to the $db
object instead of the actual object. Thats all fine, but then I came across this:
function __construct(&$db) {
$this->db = $db;
$this->date = $GLOBALS['date'];
if ($_SESSION['logged']) {
$this->_checkSession();
}
}
That code is used like this:
$db = db_connect();
$user = new User($db);
As you can see, what's actually going on is that I am passing around a reference to the DB
instance rather than the actual object. I obviously had my reasons when I wrote this code 3 years ago, so now I'm wondering, why?
Should all my "DB" classes and objects be passed by reference? Does simply passing by value, say, a PDO object, cause it to create new connections? What's correct practice and what should I be using?