dongyan6503 2013-07-29 13:22
浏览 67
已采纳

关闭函数内部的PDO连接

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;
}
  • 写回答

5条回答 默认 最新

  • douduo2407 2013-07-29 13:26
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上