Many of my classes require access to a database to do their work. For a while I’ve been doing something like the following:
// Create a (one) database object
$mysqli = new mysqli("host", "username", "password", "db");
// Pass database object into each new object that requires database interaction as follows
$car = new Car($data, $mysqli);
$plane = new Plane($data, $mysqli);
// etc
Then each class has a private $mysqli member which the passed in mysqli object is assigned to in the construct as follows:
class Car {
private $mysqli;
public function __construct($data, $mysqli) {
$this->mysqli = $mysqli;
}
}
Then class methods can use the mysqli object easily like this:
public function fuelLevel() {
$this->mysqli->query("SELECT fuel_level FROM fuel_tank");
}
My question is, will I run into any performance issues if I were to create a few thousand of these objects? Am I correct in thinking that there is only technically one database connection in my entire application by doing so? Or should I be using references (pointers?) like below to avoid the feared performance overheads?
$car = new Car($data, &$mysqli);
$plane = new Plane($data, &$mysqli);
No, this cannot possibly cause any measurable performance impact. You are correct, there is a single connection object which you’re passing by reference. This level of optimization isn’t something you should be concerned with while developing in PHP.
You should absolutely not use call-time pass-by-reference (
new Car($data, &$mysqli)), which is deprecated in PHP 5.3.