dongnunai3125 2012-01-19 06:24
浏览 25
已采纳

(PHP)从类代码中取消设置对象

Is it possible to unset (clean or un-instantiate) an object of a class by executing code of that particular class?

My scenario is one that, for some reason, I reach a point that the object has no meaning to exist anymore, so I want to make sure that is will not be used again by killing its reference in memory.

Here is a snippet example:

class Foo {
    public $bar = "doh!";
    function destroy() {
        // ???    
    }
}
$o = new Foo();
echo $o->bar . '
';
$o->destroy();
echo $o->bar . '
'; // I expect an error here...

If I do a "unset" command outside the class code, it works, obviously:

$o = new Foo();
unset($o);
echo $o->bar . '
'; // PHP Notice:  Undefined property: Foo::$bar in ...

But I tried to do it inside the "destroy" method, by calling "unset", or creating a custom "__destruct", but none worked.

Any ideas are very welcome.

Cheers,

  • 写回答

6条回答 默认 最新

  • duanlieshuang5330 2012-01-20 01:05
    关注

    Yeah, it seems impossible to achieve... another dirty way could be:

    class Foo {
        public $bar = "doh!";
        function destroy() {
            unset($this->bar); // and do this for EVERY property of this class
        }
    }
    $o = new Foo();
    echo $o->bar . '
    ';
    $o->destroy();
    echo $o->bar . '
    '; // PHP Notice:  Undefined property: Foo::$bar in...
    

    However, the object would still exists, and methods would still be accessible.

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭