13

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.
Charles
  • 50,943
  • 13
  • 104
  • 142
Wilco
  • 32,754
  • 49
  • 128
  • 160
  • 1
    gave a "yes-and-here-is-how" answer to an essentially similar question here - http://stackoverflow.com/a/21367011/1537018 – Jaak Kütt Jan 26 '14 at 18:06

3 Answers3

14

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
  • 100,734
  • 37
  • 191
  • 225
  • 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 Jul 15 '10 at 23:52
  • 1
    I think this is really the best solution that can be found, so I'm going to mark it as the accepted answer. – Wilco Aug 04 '10 at 16:43
5

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.
Warbo
  • 2,611
  • 1
  • 29
  • 23
0

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

Zippo
  • 15,850
  • 10
  • 60
  • 58
  • 1
    Increasing the scope of a value in order to have it garbage collected is backwards. Making it global causes conflicts with any existing values of the same name, plus it allows more code to access, and hence depend on, the value. This makes it *harder* to remove. Your solution will remove the value, along with any other "file" global (pre-existing or yet-to-be-added), and break any other users of any of these values. – Warbo Aug 07 '14 at 16:56