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 better and memory friendly solution to this problem. The structure is still the same but instead of filling the array we use the new keyword yield to use the numbers directly.

function gen($n) {
  $num = 0;
  while ($num < $n) {
    yield $num;
    $num += 1;
  }
}

In this foreach we can use the generator.

foreach(gen(10000000) as $key => $val) {
        echo $key . "n";
}

When using a generator in this example the memory usage decreases because PHP don’t stores the whole array into memory but uses a value en then returns the allocated memory because the value is not needed anymore or reuses it for another value. So it is a very nice addition to PHP and could be very usable when iterating through large datasets and avoid writing the same iterator class every time.

Those two changes are the largest and most important additions to PHP 5.5 in my opinion but there is more to come as PHP 5.5 has only it’s first alpha release.

One thought on “Finally PHP 5.5 is here”

Comments are closed.