类实例可以自毁吗?

Wil*_*lco 10 php oop

PHP对象实例是否有可能销毁/取消自身?假设我有一个代表文件的类,然后我随后使用该类删除该文件.我可以以某种方式从其自己的方法中取消设置实例吗?

$file = new FileClass();

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

// ... at this point $file would be seen as unset.
Run Code Online (Sandbox Code Playgroud)

Nik*_*kiC 14

不,不可能从一个不合逻辑的范围内破坏一个阶级.unset($this)不起作用(至少不如预期).

你为什么不用

unset($file);
Run Code Online (Sandbox Code Playgroud)

并定义一个__destruct函数,在其中执行您通常会执行的任务delete


War*_*rbo 5

或者,您可以限制 $file 的范围,以便在不再使用时对其进行垃圾收集:

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

// ... at this point $file would be seen as unset.
Run Code Online (Sandbox Code Playgroud)