0

What would you advise me to use performance wise between the following

A)

function db(){ return new mysqli('localhost','user','pass','db'); }

//global scope
$db = db();

function foo(){
//function scope
$db = db();

[...]

}

B)

//global scope
$db = new mysqli('localhost','user','pass','db');

function bar(){
//function scope
global $db

[...]

}

At the moment I'm using method A but I'm aware there is a overhead in calling a function and db() is called in most functions, so I was wondering.

wlf
  • 851
  • 1
  • 9
  • 15
  • 3
    Such minimal performance differences are the last thing you should worry about. [Stop using `global`](http://stackoverflow.com/questions/12445972/stop-using-global-in-php/12446305#12446305) – deceze Sep 20 '12 at 09:02
  • 1
    neither have a real impact on performance. if i would really really have to, i would use the first variant, definetly not the second – Vlad Balmos Sep 20 '12 at 09:22

1 Answers1

0

Maybe you should use an object, if you want to access your database in several place :

class db_manager {
    private $db = new mysqli('localhost','user','pass','db');

    public function getDb() {
        return $this->db;
    }
}

And call it like this :

$db = (new db_manager)->getDb();
Fry_95
  • 241
  • 1
  • 6
  • isn't that just more overhead, instantiating a class + calling its method rather than simply calling a function? As far as I know classes don't offer any benefits in terms of performance although I'm aware they sometimes make code clearer. – wlf Sep 21 '12 at 08:17
  • Using global is bad but in the first method you're creating a mysqli object everytime you're calling your function db(); so if you're focusing on performance both of your methods are ok, depending on how often you need a $db, if it's a very lot, B is better. – Fry_95 Sep 21 '12 at 08:42