tags:

views:

48

answers:

2

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 unset.
A: 

That's the only solution I can think of:

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

Then you do:

$file->delete('file');
Zippo
Won't work if `$file` isn't in the global scope though
Chris T
+2  A: 

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?

nikic
This was something I have considered. The only issue with this approach would of course be readability. Looking back at this code 5 years later, or someone looking at it for the first time, would have no way of knowing calling unset() was actually deleting the file.
Wilco
I think this is really the best solution that can be found, so I'm going to mark it as the accepted answer.
Wilco