PHP finally clause

exception, php

Solution

In the RFC for adding finally to PHP, they suggest this workaround:

<?php
$db = mysqli_connect();
try {
   call_some_function($db);
} catch (Exception $e) {
   mysqli_close($db);
   throw $e;
}
mysql_close($db);

So unless you upgrade to PHP 5.5 (which will contain the `finally` construct), this is probably your best option.

Problem

What is the best practice to simulate a finally clause? I realize this could be considered related (though I don't think it's a duplicate) of this question. However, in my case I want to handle exceptions, I want to use finally (or whatever PHP equivalent or practice) as defined by python: A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. Just loosely writing the code after the try-catch block seems like an ugly practice to me.

Original source