Search code examples
phpfunctionunset

PHP function variables and the garbage collector


I was wondering if anyone could answer me this quick question. I tried searching it but I get similar questions but in the wrong context.

What I am wondering is take this code:

function foo()
{
    $test_array = array();
    for($i=0; $i<10000000; $i++)
    {
        $test_array[] = $i;
    }
}

What happens to $test_array after the function finishes. I know that it looses scope, I am not new to programming.

What I am wondering is should I call

unset($test_array);

before the function ends or does PHP set it for deletion to the garbage collector as the function ends?

I used the for loop just to show a variable of a fair size to get my point across.

Thanks for reading Kevin


Solution

  • Once $test_array is no longer in scope (and there are no additional references that point to it), it is flagged for garbage collection.

    It ceases to be in scope when the process returns from the function to the calling routine.

    So there is no need to unset it.

    This would only be different if you had declared $test_array as static.