user4015351
user4015351

Reputation:

What is the best method for global var in function/class? PHP

my problem "is too many connection to MySQL" because i had created a new object for each function that had needed it.

What is the best solution for this operation? There is other methods?

$db = connection(); // PDO

//1
function test(){
    $GLOBALS['db']->prepare(..);
}

// 2
function test2(){
    global $db
    $db->prepare(..);
}

Upvotes: 0

Views: 60

Answers (1)

h00ligan
h00ligan

Reputation: 1481

I'd say both are bad, pass the $db object in as an argument to the functions:

function test($db) {
    $db->prepare(...);
}

Upvotes: 2

Related Questions