Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a PHP object from its class?

Tags:

oop

php

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?

like image 257
Yasen Zhelev Avatar asked Mar 03 '11 12:03

Yasen Zhelev


People also ask

How do you delete an object in PHP?

// Method 1: Set to null $var = null; // Method 2: Unset unset($var);

How do you remove an object from a class in Java?

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.

Is used to delete a variable in PHP?

The unset() function is an inbuilt function in PHP which is used to unset a specified variable.


1 Answers

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.

like image 78
mauris Avatar answered Oct 03 '22 11:10

mauris