Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP : Should I unset objects always after using them? [closed]

Tags:

oop

php

Should I always unset objects after using them? Consider the following code.

foreach ( $items as $item_id )
{
    $item = new Item($item_id);
    echo $item->name;
    unset( $item ); 
}

Is it advisable to use unset() this way? Are there better techniques to free up memory after using objects?

like image 327
Dave Avatar asked Nov 24 '11 23:11

Dave


2 Answers

In your case, no. Everytime $item is replace the old value is destroyed. The last value of $item will remain allocated, but if your code is well structured you'll be using functions and when $item goes out of scope it will finally be destroyed.

like image 83
Artefacto Avatar answered Oct 10 '22 08:10

Artefacto


Always? No. PHP has a garbage collector which will take care of removing objects from memory once they are not being used any longer.

like image 45
Tim Cooper Avatar answered Oct 10 '22 08:10

Tim Cooper