Press "Enter" to skip to content

PHP's New Feature: finally

Recently, the RFC I submitted about finally: Supports finally keyword has been committed to the PHP trunk. Today let me introduce the background and usage of this new feature.
The requirement for this feature was first raised way back in 2005: FR #32100, but no one ever went and implemented it. Last month someone brought it up again, so I gave it a try with a "let's see" attitude, because I'd been told one reason it had never been implemented was that it was hard to implement (maybe for a coder, liking to tackle hard problems is a natural inclination, hehe)..
For PHP as it stands today, if we need to do some work when an exception occurs that we can't handle at that point, we'd end up writing code like this:

function anonymous () {
   try  {
      function_may_throw_exception();
   } catch (Exception $e) {
      clearup();
      throw $e;
   }
   clearup();
}

As we can see, we need to explicitly write clearup() twice. And this is the problem that finally can solve.
finally is not an original PHP creation — C#, Javascript, Java.. and other languages all have it, and PHP's finally is similar to the ones in other languages.
A part of finally that can be a bit confusing for people is returning inside a finally. Because a finally must be guaranteed to always execute, if we return in the try, the finally will still be called. So what if the finally also returns? Which return value is the final one? In PHP, if you return in the finally, it will override the original return value.

<?php
function anonymous() {
    try {
       return 1;
    } finally {
       return 2;
    }
}
var_dump(anonymous());

You'll get int(2).
When you combine finally with exceptions, return, and nested try/catch/finally, the flow can get quite tangled. That's also part of the reason no one has been able to implement it for so long. But let's look at this finally execution flow diagram (from: Finally Getting finally In PHP?); it helps us understand the flow:

Finally execution flow

Now that we have finally, the example at the start of the article can be written as:

function anonymous () {
   try  {
      function_may_throw_exception();
   } finally {
      clearup();
   }
}

A feature like this is a lot more comfortable for those with a bit of code-cleanliness OCD 🙂
The code has been committed to PHP's trunk, but by the time everyone can actually use it, it's probably at the earliest next year (shipping with PHP 5.5).

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.