PHP 5.3

PHP 5.3.0 was release one month ago on June 30th with a couple of interesting new language features; some will make your life a bit easier, and some you will need to be aware of.

A brief summary of added features:

Namespace support, late static bindings, jump label (limited goto), native closures, native PHP archives (phar), garbage collection for circular references, vastly improved Windows support, persistent connections with mysqli, sqlite3, fileinfo as a replacement for mime_magic for better MIME support, ternary shortcut and the internationalization extension. Of these I believe the most interesting features are native closures, the ternary shortcut, and namespace support.

Closures, also called anonymous functions, allow you to create a function without a name. If you have ever programmed in JavaScript, you would have noticed they used often as callback functions. In PHP they are useful for the same thing. For example, the usort PHP function takes a callback function as an argument and would therefore be a good candidate for a one time custom sorting function:

usort($arr, function($a, $b) { return $a < $b ? 1 : -1; });

The new ternary shortcut is a very welcome syntax addition. The ternary shortcut allows a command to take the result of a variable if its set, or if its not defined or empty, fall back to a default value.

Before PHP 5.3, the syntax for getting the value would be:

$action = empty($_GET['action']) ? $_GET['action'] : 'home';

The ternary shortcut allows you to simplify this to:

$action = $_GET['action'] ?: 'home';

Namespace support is important because PHP libraries can now use regular class names without requiring prefixes. The symfony framework prefixes every single class with the ‘sf’ token so it doesn’t clash with other PHP libraries that may want to have common class names like WebController. Collisions can be handled much easier now; if two packages are using the same class names and you want to use them in the same project, just put one of them in a namespace and continue coding, problem solved.

namespace my\name;
$c = new \my\name\MyClass;

PHP 5.3 is a pretty decent update with many new feature that are critical for PHP to remain a competitive programming language. I encourage you to start thinking about how you can use these feature and even download the latest version and try them out.