douwei1408 2014-06-23 10:34
浏览 178
已采纳

PHP通过同名重新实例化类

this is actually a simple question but I haven't found a concise answer here.

suppose I instantiate a class:

$hedgehog = new Hedgehog();

and later instantiate it again with the same variable name:

$hedgehog = new Hedgehog();

does that simply destroy the previous instance? or is there a better way to approach this if I WANT to destroy the previous instance? Thanks

  • 写回答

1条回答 默认 最新

  • dqrqp8492 2014-06-23 10:51
    关注

    The process of removing unused scalars, arrays and objects is called garbage collection.

    PHP's GC is based on reference counters. As soon as there is no more reference to a zval (internal structure storing variables), it may be removed by the garbage collector.

    A nice introduction to reference counting and garbage collection is located here.

    This basic understanding is important if you e.g. create another reference to the same zval (in this case your object):

    $myHedgehog = new Hedgehog();
    $yourHedgehog = $myHedgehog;
    $myHedgehog = new Hedgehog();
    

    In this case, the old Hedgehog object will stay and $yourHadgehog will still point to it.

    More confusing even when an object references itself:

    $myHedgehog = new Hedgehog();
    $myHedgehog->father = $myHedgehog;
    unset($myHedgehog);
    

    In this case, you will lose access to the Hedgehog object because no more symbol points to it, but since there still is a reference to it, the garbage collector will not delete it.
    This also applies to an array that has a reference to itself as member:

    $myArray = array();
    $myArray['somekey'] =& $myArray;
    unset($myArray);
    

    Note the & operator that will store a reference to $myArray rather than copy the array.

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

报告相同问题?

悬赏问题

  • ¥15 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势