How crucial is object destruction in PHP? is it important to destroy objects in PHP after using them? because unlike java, PHP doesn't have a garbage collector (nothing that I know of)
Using the PHP unset() function, we can delete an object. So with the PHP unset() function, putting the object that we want to delete as the parameter to this function, we can delete this object. This is shown below. So in the above code, we delete an object named $object1.
// Method 1: Set to null $var = null; // Method 2: Unset unset($var);
In PHP, Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable. Object is an instance of either a built-in or user defined class. In addition to properties, class defines functionality associated with data.
Only the garbage collection system can destroy an object.
You don't need to destroy objects in the general case, and PHP certainly does have a garbage collector. Moreover, most simple scripts would not even really need one because the whole environment is torn down and rebuilt for every HTTP request; the garbage collector helps those scripts that would run out of memory while serving a single request.
You might want to "lose" all references to objects that consume a large amount of memory and/or wrap unmanaged resources; this is usually as easy as
$largeObject = null; // reference to previous value lost
If that was the last reference to $largeObject
, then:
gc_collect_cycles
to force garbage collection at any time).Of course all of this does not come into consideration in the typical case of "service a request and then exit".
Normally this is not an issue you have to take into account. Here is an article about one guy who met this issue.
http://paul-m-jones.com/archives/262
you can use this function to destruct whatever object you like within your classes.
function __destruct()
{
//do stuff
}
An object can remain in the memory for the duration of the request, or when invoking from command line, as long as the script remains running.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With