Destroying objects in PHP
How to destroy and object that was instantiated when it is no longer needed by our PHP script.
Edited: 2021-02-14 01:44
When an object is no longer needed it can often be safely destroyed to free up memory in the running script; there is a few ways to do this, the is to use PHP's unset function.
Instantiating an object may look like this:
$some_object = new some_object();
This object might take up memory for the duration that the script is running; of course, PHP will automatically free up the memory when the script finishes running, but sometimes it may be desirable to remove the object earlier in the process in order to free up memory.
To free up memory instantly, we can use the unset function on the variable holding the object:
unset($some_object);
This should, however, only be necessary when working with memory-heavy scripts; in addition, we might also benefit from unset in environments with a sufficiently high number of concurrent users, since each user might double the memory that is used by the PHP.
unset may be used on sufficiently long-lived variables, of any type, so it is not only useful for objects — Arrays and strings can also grow quite large.
null vs unset
Another way to destroy the contents of a variable is simply tp re-assign the variable, typically a value of null would be used:
$some_object = null;
The difference between null and unset is subtle; unset has been shown to be a tiny bit faster and free up more memory. The question is probably mostly relevant because some other languages allows you to "unset" variables by nullifying them.
Links
- unset - php.net
Tell us what you think: