PHP Version 5.5

PHP 5.5 is available. As the maintainer of PHP Mode for GNU Emacs I make an effort to keep up to date on all feature changes in PHP, especially those which demand updates to PHP Mode. I keep a ‘bleeding-edge’ development version of PHP installed for that reason, on top of the stable version that I use for everything else. Thus I was using a lot of the PHP 5.5 features during their development, and so today I want to write about the ones which I find most useful and interesting.

Finally

Exceptions now allow a finally clause, something provided by many other programming languages with a similar exception model. It is useful for grouping code that should run regardless of whether or not an exception occurs. For example:

try {
        do_something_that_could_overflow();
}
catch (OverflowException $e) {
        // ...
}
finally {
        // This code will run regardless of whether or not the
        // exception occurred.

        cleanup_resources();
}

Literal Array and String References

PHP 5.5 now allows you to reference the indices of literal arrays and strings, which is useful and consistent with referencing the return values of functions.

function foo() {
        return [10, 20, 30];
}

// Prints 20
echo foo()[1];

Generators

Personally this is my favorite new addition. Generators in PHP use a syntax that most programmers should be able to adopt easily, particularly those who use generators in other languages. A common use for generators is to represent an infinite series of data using finite space and memory. For ideas about what you can do with generators I recommend looking towards Python and JavaScript. Lua coroutines also let you do everything you can with generators and are worth a look for ideas.

Foreach Over Lists

Finally, a great new feature I like is support for the list construct in foreach-loops. As the PHP manual demonstrates:

$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    // $a contains the first element of the nested array,
    // and $b contains the second element.
    echo "A: $a; B: $b\n";
}

This is a great addition for when you need to loop through nested arrays or similar constructs.

Advertisements

Add Your Thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s