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 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题