2

I have a class that allows a PDO connection which sets itself up. When I want to use the connection I can use:

$db = $factory->create('db');

However, I wanted to just be able to do:

global $db;

Anytime I want to use the database.

Would this work?

$db = function(){
        $con = $factory->create('db');
        return $con;
    };

global $db;

This way, I can close the connection and then open it again at any point. Example:

global $db;
$db->close();
// Re-open
global $db;

Or how could I possibly do this? References would be so appreciated as I have searched a lot.

Thanks in advance.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Jaquarh
  • 6,493
  • 7
  • 34
  • 86
  • if you make `$db` global then whats the point for the factory pattern ?? just curious – Andrew Feb 17 '16 at 14:19
  • http://stackoverflow.com/questions/7792974/global-variable-database-connection – Gouda Elalfy Feb 17 '16 at 14:20
  • I am new to protected, global and private :( I want to just be able to `global $db;` every time I want to use the database and just be able to close it and re-open it the way it says. Can anyone link me any references to achieve this? – Jaquarh Feb 17 '16 at 14:20
  • While I don't know what `$db->close()` does, the connection is not going to magically reopen when you change the variable scope, which is all the global keyword is doing. – Devon Bessemer Feb 17 '16 at 14:21
  • MyBB, you can do $db->close(); & then just global $db; to reopen the connection :/ @Devon – Jaquarh Feb 17 '16 at 14:21
  • 3
    Then `$db->close()` probably isn't doing anything. You should focus your learning on the proper usage and separation of variable scopes, not trying to adapt the code to how MyBB works. – Devon Bessemer Feb 17 '16 at 14:22
  • So in this case I'll just have to do: `$db = $factory->create('db');` and then make it null and re-create it when I want to re-use it? – Jaquarh Feb 17 '16 at 14:24
  • Is this your own class? What does `$factory->create('db')` and `$db->close()` exactly do? – simon Feb 17 '16 at 14:27
  • @KyleE4K: instead of adding Solved text to topic, add an answer and accept it. – Smar Feb 17 '16 at 14:27
  • Can't accept my own answers for 2 days lol but okay – Jaquarh Feb 17 '16 at 14:28

1 Answers1

0

@Devon explained in the comments section about Scopes and how this couldn't be achieved.

In order for this to work you'd just do:

$db = $factory->create('db');
// close it
$db = null;
// re-open it
$db = $factory->create('db');

Or this:

function db(){
    $db = $factory->create('db');
    global $db;
}

db();
$db->.....
Jaquarh
  • 6,493
  • 7
  • 34
  • 86