Finally! finally in PHP 5.5

PHP 5.5.0 was released yesterday, and there are a handful of helpful new features. Among them, there is one that looks the best to me — the try-catch block has the finally block added. After all, if you’re doing exception handling in your code with try-catch (and if you’re not, you really should be), there are often scenarios in which you want to execute some arbitrary code at the end of the block, regardless of whether an error got thrown or not.

In some cases, you can put it outside the try-catch block (at the end, of course), but there are at least two circumstances where that’s less-than-optimal. First, if the program flow is altered in the try or catch, yet you want to tack on some code at the end, you’re in luck. But in our case, most of the time, it’s a readability issue. We try to group code conceptually when we write, much as we do when writing in English. That means we use sentences and paragraphs. Well, when coding, we do the same thing. And the addition of the finally block will make that even easier.

Another nifty functional help is the addition of the list form in foreach structures.If you work with nested arrays, you can now unpack them in the foreach construct, exposing the underlying variables much more easily. Like the finally block addition, it’s not as though you couldn’t code around this limitation, but when you don’t have to, code gets more readable.

In a deja-vu moment for C programmers, you can now dereference arrays and string literals to access specific items and characters. So in PHP 5.5, ‘Square’[1] equates to ‘q’. Not too shabby.

You can now pass a function call to empty() to evaluate it, which is another keystroke-saver when coding. So if you have a function foo() that may return data or may return, say, false, you can evaluate empty(foo()) and see if false came back. Again, a minor assist, but an assist nonetheless.

There are other features in this release, too, including a new Zend optimization caching extension, some enhancements to the GD graphics library, a new yield keyword that allows you to do simple iteration without using as much memory, a class function that gives you the unqualified class name, and more.

It’s good to see PHP continuing to evolve and grow — it has come a long way since I first used it fifteen years ago!