douna1895 2016-08-09 21:38
浏览 48
已采纳

PHP:这段代码会导致内存泄漏吗?

As I understand, as the reference count of an object becomes 0, PHP's garbage collector takes care of destruction of objects.

I have a utility function for database connections, where I create a PDO object and return the object to the calling script for PDO operations.

Since I have this code all over the place of the webserver scripts, which is going to serve mobile client requests, it is critical I don't overlook a detail and have memory leaks when the app goes live.

Do you see any problems here?

in connectDB.php:

function mySQLConnect() {

    .....
    .....

    try
    {
        $dbh = new PDO($dsn, $user, $password, $options);   // Ref Count=1

        ....
        return $dbh;    

    }
    catch (PDOException $e)
    {
       ....
       return NULL; 

    }
}

in a PHP script:

include 'connectDB.php';

try
{

    $dbh = mySQLConnect();     // Ref Count =2
    ....
    ....

}   //Script Stops, Ref Count becomes 0 and memory is freed- or is it?

catch (Exception $e)
{
   ....
   ....

}   

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • doudou6719 2016-08-09 23:00
    关注

    This code will not leak. As soon as you get rid of references, then PHP automatically collects the garbage. The code above is a very simple case for PHP - all the references are merely local variables. So finishing the function or the script removes the reference automatically, you don't need to do anything for that.

    And this line is not a point of concern:

    $dbh = mySQLConnect(); // Ref Count =2

    Actually, ref count there will be 1. Because, when mySQLConnect() returned the value, its variable $dbh was released, and thus reference count to the PDO object was decreased - it became 0 (but GC was not invoked yet, as the function return was in progress). At the same time the variable $dbh in the PHP script got that PDO object, thus reference to it was increased and became 1.

    Also this line is also not a concern:

    //Script Stops, Ref Count becomes 0 and memory is freed- or is it?

    The major rule here is that when a PHP script finishes - then all the objects are freed by PHP. Ref counts do not matter at this phase. PHP returns all the memory it got, because it knows that the work is over, and the variables will not be needed anymore. The next time when the PHP script is invoked, it starts from scratch - with no variables, no ref counts, no data from the previous execution.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集