TT4M.C TT4M.C - 1 year ago 93
PHP Question

PHP Destructor | unset() VS overwriting object

I have learned from this SO question that the best way to destroy objects in PHP is to use


I am wondering if I even need to destroy the object if I am essentially using the same var in a loop ...

foreach ($ids_array as $id) {
$O = new Object($id);

// stuff and things

Does this really use the same memory or am I unknowingly creating a bunch of objects and not destroying them?

Answer Source

If there's no variable left referring to an object, it will eventually get garbage collected. For that purpose it's irrelevant whether you unset the variable(s) or simply assign something else to them so they stop referring to the object.

IMO you should rarely use unset, you should rather write small functions which will automatically discard all variables in their scope when they return, which means things will get garbage collected automatically rather sooner than later and you don't need to worry much about it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download