Destroying objects in PHP

How to destroy and object that was instantiated when it is no longer needed by our PHP script.

573 views

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

  1. unset - php.net

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials