Search code examples
phpoopdestructormagic-methods

Deletion of a PHP object; also unset() and __destruct


Are these correct:

  1. Any PHP object always gets deleted after it is run (like the code of it).

  2. unset($objectName) just stimulates what would happen anyway. The deletion will be a little bit faster (from RAM memory) but in the end it is exactly the same thing.

  3. __destruct is like an event that gets run prior to deleting an object, so we can have it or not. Any code can be run within that.

Does unset() has anything to do with __destruct? Like it would just go to that (as the only step) and then delete?


Solution

    1. Variables/objects/resources get automatically deleted/deallocated when the script they're in completes execution. It is not necessary (or recommended) to call unset() on everything.

    2. If you want something to be deleted/deallocated before the end of the script, you can explicitly unset() it, and it will happen immediately rather than and the end of the script. This can free up memory, but is usually used simply to remove the possibility of the thing being referenced again.

    3. Correct.

    Does unset() has anything to do with __destruct.

    Yes. Just prior to an object getting destroyed (either by explicit unset() or by reaching the end of the script), the __destruct() method gets called if present.