2

I have a class in which class variables are set within some of the methods. The class has a __destruct() function that unsets class variables using the unset() function.

Right now I am listing all variables to unset in __destruct, but it seems like there should be a way to unset all.

For example, right now I am doing this:

function __destruct()
{
  unset($this->variable1);
  unset($this->variable2);
  //et cetera
}

Surely there's so way to unset them ALL without listing them, right?

1 Answer 1

8
foreach ($this as &$value) {
    $value = null;
}

See http://www.php.net/manual/en/language.oop5.iterations.php.

You should not unset properties, they're part of the class/object. Set them to null instead to clear their values. But: the object is about the go out of memory anyway, and all properties will go with it. There's no real need to do this.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I understand that when the script is done with an instance of an object it gets flushed, but I was trying to stick to (what I thougt) was good programming practice.
How do you do this if your class implements IteratorAggregate, and that method is applied only to a single array property of the class? How do you apply this to static properties as well?
@Butt Please post a new question, I'm not entirely sure what you're asking and comments aren't really an appropriate place to discuss in-depth technical details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.