Pregunta

I've read in PDO manual that to close connection you should use the following:

$connection = null;

However, Some people suggested that since PHP 5.3 has a new GC, the following should be used:

unset($connection);

I need to know once and for all, which one is preferred, or are they the same?

¿Fue útil?

Solución

They do the same thing. Unsetting the $pdo handle and setting it null both close the connection.

You can test this for yourself. Run the following script in one window, and in a second window open the MySQL client and run SHOW PROCESSLIST every couple of seconds to see when the connection disappears.

<?php

$pdo = new PDO(..);
sleep(10);
unset($pdo);
echo "pdo unset!\n";
sleep(10);

Then change unset($pdo) to $pdo=null; and run the test again.

<?php

$pdo = new PDO(..);
sleep(10);
$pdo = null;
echo "pdo set null!\n";
sleep(10);

The extra sleep() at the end is there to give you a moment to see that the connection has dropped, before the PHP script terminates (which would drop the connection anyway).

Otros consejos

I stumbled with this. I have a PDO object that spans setup and teardown, and I can't find where there must be a remaining reference, as setting $pdo to null did not resolve the problem.

User Contributed Notes in http://php.net/manual/en/pdo.connections.php discusses the problem of delayed closure. Here they suggest killing the current connection:

$pdo->query('SELECT pg_terminate_backend(pg_backend_pid());'); $pdo = null;

This is for postgres. For mysql I have used:

$pdo->query('KILL CONNECTION CONNECTION_ID();');

using

$pdo = null; //is an assignment to null; the variable still declared in the memory.

but

unset($pdo); // will call the function to distroy also the adress "@" pointed by the variable.

so using unset is prefered.

Just don't bother with closing at all. PHP will close it for you all right.

Note that of course your application have to be sanely designed, without the need of reconnecting to different databases at a rate of machine-gun. And even in latter case, the method you are using to close would be the least problem. You are barking wrongest tree ever. Work the number of connections, not the way you are closing them.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top