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条)

报告相同问题?

悬赏问题

  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥50 vue router 动态路由问题