I know that for some that might sound stupid, but I was thinking if I hava a delete() method in a class that removes all the object data (from DB and file system), how can I
Whilst developing on a framework, I came across such issue as well. unset($this)
is totally not possible, as $this
is just a special pointer that allows you to access the current object's properties and methods.
The only way is to encapsulate the use of objects in methods / functions so that when the method / function ends, the reference to the object is lost and garbage collector will automatically free the memory for other things.
See example RaiseFile
, a class that represents a file:
http://code.google.com/p/phpraise/source/browse/trunk/phpraise/core/io/file/RaiseFile.php
In the RaiseFile class, it'll be sensible that after you call the delete() method and the file is deleted, the RaiseFile object should also be deleted.
However because of the problem you mentioned, I actually have to insist that RaiseFile points to a file whether or not the file exists or not. Existence of the file can be tracked through the exists()
method.
Say we have a cut-paste function that uses RaiseFile representation:
/**
* Cut and paste a file from source to destination
* @param string $file Pathname to source file
* @param string $dest Pathname to destination file
* @return RaiseFile The destination file
*/
function cutpaste($file, $dest){
$f = new RaiseFile($file);
$d = new RaiseFile($dest);
$f->copy($d);
$f->delete();
return $d;
}
Notice how $f
is removed and GC-ed after the function ends because there is no more references to the RaiseFile
object $f
outside the function.