Martin
Martin

Reputation: 123

Are variables used in PHP functions automatically unset after function execution?

I have a question regarding the variables/arrays used in PHP functions. After executing the function, are all the variables automatically unset? If not, when do they unset exactly, after executing the whole PHP page? After a certain time?

Is it useful to unset all variables used in a function at the end of the function to release from memory?

Thank you in advance for your help and comments!

Upvotes: 12

Views: 6752

Answers (3)

Matthewhall58
Matthewhall58

Reputation: 102

Yup, anything not declared a global INSIDE a function will not exist outside the function. Once the function executes, the values are no longer in mem.

PHP: Variable Scope

Upvotes: 1

alex
alex

Reputation: 490481

Yes, they are deallocated once their scope is finished with (function returns).

I don't think their memory is automatically cleared though, rather, they will be cleared when additional memory is required.

Upvotes: 0

Wes
Wes

Reputation: 6585

Local variables that are defined and used in a function are not automatically unset after the function is executed. Rather they are marked for collection by the garbage collector. Unless you are consuming large amounts of memory with the definition of a local variable there really isn't a need to explicitly unset them. Just let the garbage collector do its job.

Upvotes: 9

Related Questions