Fun with PHP 5.3
02 September, 2009
Version 5.3 has been out a little over two months, so it's nigh time I dug into into it! It's surprising that I've waited this long to get around to installing it, as it contains some tidbits that I have been eagerly awaiting since talk about PHP 6 began a couple years ago. In addition to the usual bug fixes, this version includes support for two features of particular interest to me: namespaces and variable static method calls.
Variable Static Method Calls
One of the biggest annoyances prior to 5.3, was that one couldn't call the static method of a class using a variable. The following code, for example, just plain would not work:
It is a very small change, but it makes all the difference in the world when using factories, builders, and singletons. Consider the following animal classes:
If you have ever used the singleton pattern, you know that the key to fetching object instances is to call the instance() or similarly named function statically. Prior to 5.3, it was impossible to dynamically call upon singletons without using trickery, such as the call_user_func or call_user_func_array methods. Now, it is very easy to simply use the syntax demonstrated above.
Another situation where the dynamic call proves useful is when trying to fetch the constants of a particular class. In the past, the developer was forced to instantiate the class, and then use a custom function to fetch the constant and return it, or worse yet, use Reflection methods to try and parse the constants from the class. As of 5.3, it's very easy to do the following:
Namespaces
PHP has long needed support for namespaces, and even though the new implementation is a little weird, it is certainly better than nothing (for most of us). At first, I was a little put-off by the Backslash delimiter (\) used for namespaces, as it is a departure form the C-like syntax that PHP usually honors. After a few uses, however, I found the PHP implementation quite easy to use, and could really care less whether it irks the C zealots who already hate PHP for a million other reasons besides this one.
The following code sample contains some different examples to try out:
In a real-world implementation, I would caution against placing multiple namespaces in the same file, but if you absolutely had to, you could use the bracket method to declare your namespaces in addition to methods outlined above. This only works if you place your namespaces in a separate file, with no additional code among them. Consider the following:
If you placed the above code in a file named bracketed_ns.php, you could call the appropriate classes in the same fashion as the previous examples:
If you are interested in checking out additional changes in version 5.3, head on over to the php.net release announcement page for a full list of new features.



