douna1895 2016-08-09 21:38
浏览 48


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() {


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

        return $dbh;    

    catch (PDOException $e)
       return NULL; 


in a PHP script:

include 'connectDB.php';


    $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 问题描述:给定一个算术表达式,通过程序求出最后的结果
    • ¥15 spyder运行重复
    • ¥15 我考考你,这代码是对的还是错的?
    • ¥15 我用C语言easyx图形库绘制了一个3d游戏方框透视,但进入游戏时候鼠标准星对准方框边缘 鼠标光标就会弹出来这是啥情况怎样让光标对准绘制的方框点击鼠标不弹出光标好烦这样
    • ¥20 用Power Query整合的问题
    • ¥20 基于python进行多背包问题的多值编码
    • ¥15 相同型号电脑与配置,发现主板有一台貌似缺少了好多元器件似的,会影响稳定性和使用寿命吗?
    • ¥15 C语言:数据子序列基础版
    • ¥20 powerbulider 导入excel文件,显示不完整
    • ¥15 paddle训练自己的数据loss降不下去