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 destroy/remove the object from within the class.
This is a PHP question. Something like unset($this);
Is it possible and wise? And what is the right way to do it?
// Method 1: Set to null $var = null; // Method 2: Unset unset($var);
The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List. Parameters: It accepts a single parameter obj of List type which represents the element to be removed from the given List.
The unset() function is an inbuilt function in PHP which is used to unset a specified variable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With