0

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(..);
}
  • 4
    A normal function argument?(But the nicer way is @RobP with a class!) – Rizier123 Dec 09 '14 at 17:13
  • 1
    The best solution may not be a global at all, but rather a singleton class that keeps the connection around. – RobP Dec 09 '14 at 17:15
  • @RobP that's only slightly better. But it's a viable solution in some cases. – Rangad Dec 09 '14 at 17:15
  • @Rangad I disagree it's only slightly better. What's your reasoning? – RobP Dec 09 '14 at 17:17
  • @RobP To have the connection nice and clean in one class which you can easy extend and look at is for me the nicest and cleanest way! You can tell in one sentence where all the code about the connection is. – Rizier123 Dec 09 '14 at 17:19
  • @Rizier123 yes I agree. – RobP Dec 09 '14 at 17:21
  • any example? i don't have understood very good singleton –  Dec 09 '14 at 17:24
  • Compared to the global approach it's a massive step up (should edit my comment, came out a bit wrong). However, as a starting point: http://programmers.stackexchange.com/a/40610 (ignore the java talk, everything except multi threading applies to php) http://stackoverflow.com/a/138012/2912456 . However, as I should've edited in, in most cases if you have no special requirements it's still a viable solution. – Rangad Dec 09 '14 at 17:25

1 Answers1

2

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

function test($db) {
    $db->prepare(...);
}
h00ligan
  • 1,441
  • 9
  • 15