Finally PHP 5.5 is here

Yes, the pun is intended. With the release of the first PHP5.5 alpha support for the finally keyword is now supported. Earlier I wrote that I think PHP has a lot of catching up to do compared with other languages like Python, Java and C#. Now it looks like that is going to happen with the new coming release of PHP 5.4.

Finally keyword

There is not much to explain 🙂 Everyone who has experience in Java or other bug OO languages already know what is does.

try {
    // Do something
} catch(Exception $e) { 
    // Catch the exception that happens
} finally { 
    // Always execute after handling the exception or when no exception has occured

Yield keyword and generators

To explain the need for generators I’ve modified the Python example to PHP. Suppose we want to make a list of numbers where we want to iterate through. The following function could be an (naive) implementation.

function gen($n) {
  $result = array();
  $num = 0;
  while ($num < $n) {
    $result[] = $num;
    $num += 1;
  return $result;

This code builds an array with a list of numbers from 0 to $n. The function returns the array and that array can be used in an foreach. It works but when using large numbers for $n the memory usage also increases. For $n = 100000 I have recorded a memory usage of 14mb. And for $n = 1000000 I get an “allowed memory size of 134217728 bytes exhausted”. This is because we store all numbers in memory and after that is done we start using the numbers.

With generators we can create a