5 ms·
Question: when are PHP's object destructors called ? I can see some issues with external resources if an object instance hangs around until it is garbage colle
by TimJYoung 16y ago
Question: when are PHP's object destructors called ? I can see some issues with external resources if an object instance hangs around until it is garbage collected. PHP might not have an issue with this if it does GC for every page load, but other languages like the .NET languages can experience serious issues if you don't release external resources using a finally block, and rather rely on the destruction of the object to release them. In such a case, the destruction may take place a long time after the initial acquisition of the external resources.
My point is that object lifetime <> external resource usage duration in all cases.
- wvenable 16y ago> when are PHP's object destructors called ? As soon as there are no more references to it. PHP is reference counted (with cycle detection). As soon as the variable containing an object goes out of scope, the destructor will be called. The fact that Java/C# destructors aren't called immediately (and may not be called at all) is the primary reason that Java has the finally block (C++ doesn't) and why C# also has the using statement.
- TimJYoung 16y agoThanks for the response. I knew that PHP was reference counted, but what I was asking (not particularly well) was more along the lines of: is it possible to have objects live longer than the scope of a single script ? IOW, is there a point at which the PHP runtime decides that it is going to collect/reclaim everything, similar to a process termination in the OS ? Or is it literally possible to implicitly allocate objects in a global fashion and have them stick around until the PHP runtime itself is terminated ? Thanks again.
- wvenable 16y agoWhen a single script terminates, all the memory is deallocated. Basically, as you said, it's just like process termination in the OS.
- TimJYoung 16y agoThanks. That's what I thought, but I'm fairly new to PHP, and wasn't entirely sure.
- dan_netwalker 16y agoWell, in fact you could serialize/unserialize the objects and store them somewhere, making use of the "magic" functions __sleep() and __wakeup(), if I recall correctly. But yes, as soon as the web server ends the response or the script gets to the end, it's finished