PDO MySQL连接关闭-未设置vs空 [英] PDO MySQL Connection close - unset vs null

查看:93
本文介绍了PDO MySQL连接关闭-未设置vs空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了PDO手册,要关闭连接,您应该使用以下命令:

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

$connection = null;

但是,有人建议,由于PHP 5.3具有新的GC,因此应使用以下内容:

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?

推荐答案

他们做同样的事情.取消设置$pdo手柄并将其设置为null都会关闭连接.

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

您可以自己测试.在一个窗口中运行以下脚本,然后在第二个窗口中打开MySQL客户端,每隔几秒钟运行SHOW PROCESSLIST,以查看连接何时消失.

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);

然后将unset($pdo)更改为$pdo=null;并再次运行测试.

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);

在PHP脚本终止之前,多余的sleep()可以让您有一段时间看到连接已断开(无论如何都会断开连接).

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).

这篇关于PDO MySQL连接关闭-未设置vs空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆