0

Say that I am using the stream resource type to open a file:

$file = fopen('1.txt', 'w+');

If I want to destroy the resource, I would call fclose():

fclose($file);

But I think that fclose() only destroys the resource and not the variable itself, I know this because when I do the following:

<?php
    $file = fopen('1.txt', 'w+');
    fclose($file);

    xdebug_debug_zval('file');
?>

I get the following result:

file:

(refcount=1, is_ref=0),resource(3, Unknown)

Which means that the variable still exist in memory.

So should I call unset($file) after calling fclose($file) to destroy the variable?

user7681202
  • 141
  • 3
  • [php free variable memory](https://www.google.com/search?q=php+free+variable+memory&rlz=1C5CHFA_enUS688US688&oq=php+free+variable+&aqs=chrome.0.0j69i57.4750j0j9&sourceid=chrome&ie=UTF-8) – SaganRitual Mar 16 '18 at 00:26
  • You should see the answer for that question in [this post](https://stackoverflow.com/questions/584960/whats-better-at-freeing-memory-with-php-unset-or-var-null) – IFebles Mar 16 '18 at 00:41

1 Answers1

1

So should I call unset($file) after calling fclose($file) to destroy the variable?

In my opinion, no, you shouldn't unset after fclose.

Here's why:

  • You don't save much memory and PHP does garbage collection anyways.
  • You make your code more noisy which means less readability and less maintainability for little to no benefit.

Of course there are some cases where unset makes sense or is needed.

I found a nice read about unset() where you can learn more.

Marco
  • 7,007
  • 2
  • 19
  • 49
  • *"and PHP does garbage collection anyways"* But the variable `$file` still have a `refcount` of `1` after calling `fclose($file)`, so it wouldn't be garbage collected, or will it? – user7681202 Mar 16 '18 at 02:06
  • @user7681202 Since this variable is globally defined it will be garbage collected once the script has ended. – Marco Mar 17 '18 at 09:34