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.

10
  • if you make $db global then whats the point for the factory pattern ?? just curious Commented Feb 17, 2016 at 14:19
  • stackoverflow.com/questions/7792974/… Commented Feb 17, 2016 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? Commented Feb 17, 2016 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. Commented Feb 17, 2016 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. Commented Feb 17, 2016 at 14:22

1 Answer 1

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->.....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.