How to destroy an object?

PandemoniumSyndicate picture PandemoniumSyndicate · Jan 10, 2012 · Viewed 177.3k times · Source

As far as I know (which is very little) , there are two ways, given:

$var = new object()

Then:

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

Other better method? Am I splitting hairs here?

Answer

Frankie picture Frankie · Jan 10, 2012

You're looking for unset().

But take into account that you can't explicitly destroy an object.

It will stay there, however if you unset the object and your script pushes PHP to the memory limits the objects not needed will be garbage collected. I would go with unset() (as opposed to setting it to null) as it seems to have better performance (not tested but documented on one of the comments from the PHP official manual).

That said, do keep in mind that PHP always destroys the objects as soon as the page is served. So this should only be needed on really long loops and/or heavy intensive pages.