dongwei3336 2011-01-17 16:18
浏览 78
已采纳

PHP的gc_enable函数究竟做了什么?

Before you tell me to read the manual, check out the php.net documentation for this function:

Warning
This function is currently not documented; only its argument list is available.

That was helpful!

This page explains that it enables garbage collection for cyclic references. Where and when is this useful? Could someone show me an example of its use? Preferably an example where a cyclic reference is created and then collected.

  • 写回答

3条回答 默认 最新

  • dongzhuang2030 2011-01-17 16:25
    关注

    gc_enable is only needed if you call gc_disable. There is really no sane reason to do this, as that would cause cyclic references to not be garbage collected (like pre-5.3, when the cyclic GC did not exist).

    PHP's garbage collector works by reference counting. You can think of a variable as a "pointer" to an object. When an object has no pointers to it, it is "dead" because nothing can reach it, so it is garbage collected.

    //one thing points to the Foo object
    $a = new Foo();
    
    //now two things do
    $b = $a;
    
    //now only $b points to it
    $a = null;
    
    //now nothing points to Foo, so php garbage collects the object
    $b = null;
    

    Consider this though:

    $a = new Foo();
    $b = new Bar();
    $b->foo = $a;
    $a->bar = $b;
    
    $a = $b = null;
    

    At this point nothing is holding on to $a or $b except the objects themselves. This is a cyclic reference, and in previous versions of php (< 5.3), would not be collected. The cyclic collector in 5.3 can now detect this and clean up these objects.

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

报告相同问题?

悬赏问题

  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决