I'm displaying a relatively "heavy" PHP page. I have several functions that each use a connection to the DB to grab some rows. I've noticed that making a new $con in each function slows things down a lot, so naturally I would like to use the same $con for each function on the page. I tried this:
$con = mysqli_connect("localhost","root","root", "mydb");
function fA($a, $b, &$con = $con)
{}
function fB($a, &$con = $con)
{}
You can see I'm trying to pass a pointer to $con for each function, but I get a syntax error, unexpected $con
for each one. (I could pass $con to the functions whenever I call them but doing it this way I don't have to go back and change every function call, and it looks neater)
You can use:
global $con;
At the beginning of each function's body like so:
function fA($a, $b) {
global $con
// ...etc...
}
But this is generally viewed as a bad practice.
A better approach would be to use dependency injection so that your logic would not be dependent on the kind of storage device given to it. Something along these lines:
class LogicExecutor {
private $con;
public __construct($con) {
$this->con = $con;
}
public function doTaskOne($a, $b) {
// you can use $this->con in this scope
}
}
$con = mysqli_connect('localhost', 'root', 'root', 'mydb');
$le = new LogicExecutor($con);
$le->doTaskOne('a','b');
But even that would couple your code to mysqli
very tightly. Have you considered an ORM?
Using global $con is ok, best solution is put the stuff into a class.
If you sticked to your original concept, you should pass $con on every function call.
$con = mysqli_connect("localhost","root","root","mydb");
fA("abraca","dabra",$con);
fB("hocus-pocus",$con);
function fA($a, $b, &$con)
{}
function fB($a, &$con)
{}
Maybe it's better to use $con as the first parameter.