Skip to content
Advertisement

Does PHP support the RAII pattern? How?

Most resources on PHP never touch memory management because the language itself is pretty good at doing this for you. However, in PHP you often end up dealing with external resources which aren’t memory — database handles, sessions, database transactions, etc. These external resources could be managed most cleanly using some form of RAII object.

I initially thought that PHP used a garbage collection scheme similar to the JVM or the CLR, where the concept of a destructor does not exist. (Remember: Everyone thinks about garbage collection the wrong way — finalizers are not destructors!) There’s the special __destruct method, but I thought that was a “finalizer” similar to a Java or C# finalizer. For this reason, you cannot use RAII on the JVM or the CLR (C#’s using blocks get you about 95% of the way there, but that’s a bit different…).

However, Google seems to indicate that PHP supports the RAII pattern, though I cannot find verification of this in the PHP docs. Does the language support this and is putting the cleanup logic in __destruct sufficient for accomplishing RAII tasks?

Advertisement

Answer

This is nearly the same question as Is destructor in PHP predictable? and the answer is the same. PHP uses refcounting, and it promises that the destructor will be called immediately as soon as the refcount goes to zero (generally when the object goes out of scope). So if you create an object and take care not to leak it out of scope, RAII is viable.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement