How does garbage collection work in PHP? Namely, how do local function variables get cleaned up?
If I assign a value to variable that is not declared global inside a function will that variable be unset automatically when function terminates or will it only be unset when the PHP script finishes executing?
I'm trying to determine if it's smarter to unset temporary, function scope variables within the function manually or to not worry about because they will be automatically unset by the 开发者_开发百科PHP engine.
The variable will be unset when the function exits, unless it has external references to it which would keep it "alive". Whether the actual memory the variable occupied is freed or not is entirely up to the garbage collector. GC is an expensive operation, and PHP will only invoke it when needed (e.g. memory's getting tight).
That entirely depends on the scope of the function. Theoretically, you could have your entire script run within the scope of one function (hopefully one that calls other functions, but still...).
For a reasonably sized function with minimal side-effects, it is perfectly fine to leave your objects set -- their destructors will be called upon completion of the function (that is the second effect of unset) and they will be cleaned up during the first cleanup cycle after the function is complete. For a larger function which involves the creation on a large number of objects, then it might be better to manually remove the objects.
The Zend Engine will do the cleanup for you, decrementing reference counts as needed.
精彩评论