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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵