Drahcir
Drahcir

Reputation: 11972

Closing PDO connection inside function

In this PHP documentation it gives the following example of how to close a connection:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// use the connection here


// and now we're done; close it
$dbh = null;

But what if I'm using it in a function where $dbh has only local scope, do I have to set it to null, or will the connection close when the function returns?

In my below example, is the connection closed?

public function doDBWork(){
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
    // use the connection here

    return true;
}

Upvotes: 1

Views: 981

Answers (5)

kwolfe
kwolfe

Reputation: 1683

A better way might be dependency injection so that you don't have to open multiple connections.

class MyClass {
    protected $PDO;

    public function __construct(PDO $PDO) {
        $this->PDO = $PDO;
    }

    public function DoDbWork() {
        $this->PDO->Query(); //uses same PDO instance that was supplied outside class
    }
}

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

//call multiple functions, do stuff procedurely, etc.
$t = new MyClass($dbh);
$t->DoDbWork();

$dbh = null;

Upvotes: 0

Jim
Jim

Reputation: 22656

Strictly speaking setting $dbh to null doesn't close the connection. This will make the PDO instance eligible for garbage collection (as long as there aren't any other references to the object). Presumably the destructor for PDO cleans up the connection.

To answer your question your example will close the connection (or at least act in the same way as the first example) because once again $dbh will be eligible for garbage collection.

Upvotes: 1

Guerra
Guerra

Reputation: 2790

PHP PDO manage the connection for you. You can make sure that connection will be closed setting null to PDO connection object. But isn't necessary.

In you case, you aren't using your connection to make querys, and when the method end the connection will be closed.

Upvotes: 1

silkfire
silkfire

Reputation: 25945

You can pass the DB handle as an argument to a global function (or static method). But it is really unnecessary. The DB handle is automatically closed when code execution ends. No need to explicitly close it.

function close_connection(PDO $dbh) {
   $dbh = null;
}

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 72981

Per the documentation:

you [close the connection] by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.

So the connection will not be closed at the end of the function since you did not assign null. Although it is inaccessible since its scope is local to the function, it technically won't be closed until the end of the script.

Note: In general, I don't recommend establishing and closing database connections within function calls.

Upvotes: 3

Related Questions