开发者

Can a class instance self-destruct?

Is it possible for a PHP object instance to destroy/unset itself? Say I had a class that represented a file, and then I subsequently delete that file using the class. Can I somehow unset the instance from within one of its own methods?

$file = new FileClass();

$file->copy('/some/new/path/');
$file->delete();

// ... at this point $file would be seen as u开发者_运维百科nset.


No, it is not possible to destruct a class from within which is illogical. unset($this) will not work (at least not as expected).

Why don't you use

unset($file);

and define a __destruct function in which you perform the tasks you would normally perform in delete?


Alternatively, you can limit the scope of $file so it gets garbage collected when no longer used:

call_user_func(function() {
  $file = new FileClass();
  $file->copy('/some/new/path/');
  $file->delete();
});

// ... at this point $file would be seen as unset.


That's the only solution I can think of:

function delete($var_name) {
   unset($GLOBALS[$var_name]);
}

Then you do:

$file->delete('file');

Anyway, a class can't suicide (without help from outside).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜