views:

61

answers:

4

I've made a class that acts like an file wrapper. When user call delete method, i want to unset the object (actually $this). Is there a way (workaround) to do that? The manual said no, there is no way...

+3  A: 

As far as I know, there is no way to destroy a class instance from within the class itself. You'll have to unset the instance within its scope.

$myClass = new fooBar();
unset($myClass);

Somewhat related: Doing the above will automatically call any existing __destruct() magic method of the class so you can do any additional cleanup. More info

Mike B
A: 

Hi,

Put your delete code in the destructor if you want to get rid of the object and the file it wraps at the same time. Then just unset the object instead of calling a delete method.

Alin Purcaru
I thought of this too, but it will delete the file automatically at the end of the script's execution :) There seems to be no way to distinguish between an explicit `unset` and the end of the script.
Pekka
Tough luck then. You'll just have to use 2 calls `->delete()` and then `unset`. Or rethink your design.
Alin Purcaru
A: 

The manual is right. There is no way.

unset is used essentially to say "I'm finished using a particular variable; it can be considered for garbage collection as far as I'm concerned.

The trouble is that $this only makes sense in the context of a method call anyway. Once the method completes, $this will fall out of scope (essentially) and will no longer count as a reference to the object. (For practical purposes.)

So you don't need to worry about freeing up $this. PHP will take care of that.

What you're probably trying to do is unset the other variables that might reference the same instance. And unless you have access to those from within the method, you can't touch them, much less unset them.

VoteyDisciple
A: 

Well, No, only the other way around, you can use the magic __destruct() function:

 public function  __destruct() {
    //delete file
 }

This will be triggered when someone unset() the Object AND when the script ends. But an Object can't destroy itself.

Hannes