Tom
Tom

Reputation: 336

When is PHP variable destroyed automatically?

I am dealing uploading large .jpg image and then manipulating it through variables. At one place, I have;

$image = imagecreatefromjpeg($_FILES['smileimage']['tmp_name'])

And then later on, in a if case, I have to $image = $newImage; and after doing some work, I want the variables to be destroyed, thinking if I don't destroy them, they might just keep on eating the RAM. So I did as following:

if(isset($newImage)) {
    imagedestroy($newImage);
}
imagedestroy($image);
imagedestroy($thumbnail);

But this provides an error as

Warning: imagedestroy(): 11 is not a valid Image resource in...

It tells erros is in line of imagedestroy($image). But $image is a valid image resource. Is it that if I destroy $newImage, $image is also destroyed automatically??

But if I remove the line which says;

if(isset($newImage)) {
    imagedestroy($newImage);
}

then, there is no error. But I am worried that, if I don't destroy $newImage if it is set, it might just persist on the RAM and eat up the whole memory at some point?? What should I do? And also, I want to know when is the variable destroyed automatically??

Upvotes: 0

Views: 303

Answers (1)

user703016
user703016

Reputation: 37975

Since you do $image = $newImage both variables refer to the same image. No copy is created. Both variables are just two different names referring to the same resource.

When you free the resource held by $newImage with imagedestroy($newImage) you are freeing the same resource that is held by $image, since they share it.

This is why the second call to imagedestroy fails, because the image no longer exists.

If you didn't manually call imagedestroy, PHP would have done it automatically at the end of the script.

Upvotes: 3

Related Questions