Back in January we looked into some of the new features that PHP 5.4 provided developers with, from Traits to Array Dereferencing. PHP 5.5 was recently released so we've put together some insight into how you can update your code to take advantage of the new features.

What's new in PHP 5.4 and PHP 5.5?

Implementing Namespaces

Namespaces have been around for years but have only recently been picked up with more developers implementing a structured hierarchy to their code. Overall namespaces are easy to implement across your projects. To setup a namespace for your code, you need to add the namespace declaration as the first statement in your code:

namespace Application;

Any subsequent directories would be represented as:

namespace Application\Controllers; 
namespace Application\Controllers\Admin;

You can use the shorthand representation of classes in your code by adding the use statement below your namespace:

# Declare our namespace
namespace Application\Controllers\HomeController;
# We need the model
use Application\Models\HomeModel as HomeModel;
# Global classes, provides failsafe for un-namespaced
use \PDO as PDO;

Now you can reference the 'HomeModel' class in your code by using:


Referencing Namespace Classes

So now you've setup your project to take advantage of a namespace hierarchy, but how do you reference classes in your project? As you can see from the examples above, referencing namespaces can be a laborious process when your directories nest into a large hierarchy. Now you can use the class keyword to return the fully qualified name of a class:

# Define namespace
namespace Application;
# We need to include this
use \Application\Controllers\HomeController;
# Our example class
class ExampleClass {
# Get the class name, will return 'Application\ExampleClass'
echo ExampleClass::class;
# Instantiate a new class
$class = new HomeController::class;

Generators and Yield

Generators provide developers with the ability to iterate through large arrays without their applications consuming large volumes of memory. Using generators also provides an easier way to handle iterative loops without having to write a class that implements the Iterator interface, something that typically adds an additional level of complexity and maintainability to your code. So if not only making a long-winded much simpler it can significantly reduce the size and complexity of the PHP code that developers have to write - just what we want!

The functionality behind a generator comes from implementing the new yield keyword into your iterative blocks. On the surface, a generator looks very similar to a normal function, but instead of returning a value, a generator may yield any number of values that'll consequently be processed and interpreted individually. This means when a generator function is called, it returns an object that can be iterated over. When you iterate over that object (for instance, via a foreach loop), PHP will call the generator function each time it needs a value, then saves the state of the generator when it yields a value so that it can be resumed when the next value is required.

To illustrate the power and use of generators, we can consider PHP’s range() function, which returns an array of the values between the $start and $end arguments. When we use the range() function, PHP will internally construct an array in our memory and, once constructed, it'll return the entire array:

 * Iterate through an array with x elements
foreach (range(0, 50000) as $number) {
    echo $number;

The problem with this is that the array returned will occupy a lot of memory, and our application can't actually start doing any processing until the array has been completely constructed. Obviously in our situation above, we're only dealing with a very simple example, but there are a lot of real-world situations where the array data will both be extremely large and complex in itself. To overcome this issue, we can adjust our function to take advantage of the new yield keyword:

function generateRange($start, $end) {
    for($i = $start; $i <= $end; $i++) {
         yield $i;
foreach(generateRange(0, 50000) as $value) {
    echo $value;


The Zend Optimiser+ opcode cache has been added into PHP 5.5 as the new OPCache extension that'll now become the default cache handler.

OPCache improves performance of any applications by precompiling your code into bytecode in shared memory. Then, when requested, it can just interpret the already compiled code. OPCache automatically detects if the cache has been modified, and whether it should re-compile the bytecode.


Traits are a way for a developer to implement and reuse common sets of methods in classes. Traits are similar to interfaces and abstract classes in that they cannot be instantiated, however they overcome the single-inheritance PHP problem by allowing classes to inherit and use multiple traits. This is a great way for developers to create helper or utility classes that can be reused across their other classes, without requiring any additional object pattern, such as the Singleton class pattern.

The best use of traits is demonstrated when multiple classes share the same functionality. For instance, a website may need to use the Facebook and Twitter APIs, all requiring a common cURL wrapper to send the API requests. Additionally, each may need to implement the OAuth protocol, handling access tokens and application keys.

 * cURL wrapper class
 * Implements all the basic functionality of cURL we'll require
trait cURL {
    public function curl($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        return $output;
 * OAuth wrapper class
 * Implements any OAuth handling methods, getting the access tokens, fetching resources, etc.
trait OAuth {
    public function getAccessToken() {
        # Return the access token
    public function getAccessCode() {
        # Return the access code
 * Twitter API Class 
class TwitterAPI {
    # Use the trait (inheritance)
    use cURL;
    public function get($url) {
        $accessToken = $this->getAccessToken();
        return json_decode($this->curl(''.$url));
 * Facebook API Class 
class FacebookAPI {
    # Use the trait (inheritance)
    use cURL;
    public function get($url) {
        $accessToken = $this->getAccessToken();
        return json_decode($this->curl(''.$url));

An abstract representation of implementing Traits is:

# Trait A
trait A {
    public function outputA() {
        return 'A';
# Trait B
trait B {
    public function outputB() {
        return 'B';
# Our class we'll instantiate
class SimpleAB {
    # Use the trait (inheritance)
    use A, B;
    public function output() {
        echo $this->outputA().' + '.$this->outputB();
# Create object, output!
$simpleAB = new SimpleAB()->output();

By using traits in your application, you can apply the multi-inheritance of the cURL and OAuth classes into your code, without any redundant/repeated code. This makes your code reusable across any other applications, and follows the DRY (Don’t Repeat Yourself) principle.

Array Shorthand and Dereferencing

Last time we looked at how you'd now be able to dereference any element in an array. I wanted to re-iterate this point as I think its something that so many developers are used to not being able to do, that they'll simply stick to the much longer methods. However, it's perfectly viable to implement arrays and reference them as seen below:

# The old way
$fruits = array('apples', 'oranges', 'bananas');
# Same as JSON literal array
$fruits = ['apples', 'oranges', 'bananas'];
# Associative array
$array = [
    'foo' => 'bar',
    'bar' => 'foo'

You're also now able to dereference an element directly from the result of a method call:

function fruits() {
    return ['apple', 'banana', 'orange'];
# This will output 'apple'
echo fruits()[0];

On top of this, you're able to do the same approach for string literals. Say you want to check the 3rd character in a string, perhaps checking for the presence of a dot or a keyword?

# Our string literal
$string = 'ALJT Media';
# This will output 'L'
echo $string[1];
# Similarly, you can directly call
echo 'ALJT Media'[0];


Typehinting allows a developer to specify what type of value they expect a method call to receive. As of PHP 5.1, this could of been either array or an object. From PHP 5.4, this'll include the new callable keyword. So what does this mean?

# Object type
class Configuration {
# Create a test class
Class TypeHintingCheck {
    public function __construct(Configuration $config, callable $next) {
# What PHP expects
$config = new Configuration;
$check = new TypeHintingCheck($config, function() {
    echo 'Loaded..';

If you pass anything but a 'Configuration' class object as the first parameter, PHP will produce an error. Similarly, if you pass anything other than a callable function, PHP will produce an error. So what types of callable variables can you pass?

function callableTesting(callable $run) {
# Anonymous functions
callableTesting(function() {});
# Callback function
# Using a class name, static method - with array shorthand
callableTesting(['Class', 'staticMethod']);
# Using a class name, static method - array longhand
callableTesting(array('Class', 'staticMethod'));
# Using a class, as a method call
callableTesting([(new ExampleClass), 'methodName']);

High-precision Page Timing

PHP 5.5 has made it easier for developers to test the performance of their applications and see how long they're taking to execute.

The global variable $_SERVER['REQUEST_TIME_FLOAT'] has been added, with microsecond precision (float) - as returned when calling microtime().

Password Hashing

The new password hashing API is finally a great solution for developers to handle encryption of passwords without having to dive into the poorly documented crypt() functions. PHP 5.5 introduces a simplified set of functions to handle password hashing that aim to make it easier for developers to understand and implement secure password hashing on their applications, without requiring the time or complexity of understanding the inner-workings of the encryption algorithms.

The API adds two new functions:

# Returns a strong hash using bcrypt
password_hash($password, PASSWORD_DEFAULT)
# Verifies the password hash - simples?
password_veriify($password, $hash);

The API currently uses bcrypt by default with it being the first release. Though we should expect to see additional algorithms implemented in the future to provide even more secure methods of hashing. If you're not a fan of the default bcrypt, you can specify your own factor to adjust the strength of the hashes produced, and can also use your own salts instead of the automatic salt generation, though they strongly suggest not too.


As is standard in pretty much every other language, PHP 5.5 has finally (get it) added the 'finally' keyword which has been a highly requested feature for several years.

The finally statement is added onto the try-catch exception blocks and allows developers to specify some code that'll always be run, regardless of whether an exception was thrown or not.

# Example of throwing errors
function testErrorHandling() {
    throw new Exception("Failed");
# Try-Catch blocks
try {
catch (Exception $e) {
    echo $e->getMessage();
finally {

Foreach Changes

With PHP 5.5, you're now able to use the list() method directly in the foreach loop:

# Shorthand array
$data = [
    [1, 'Lewis'],
    [2, 'Adam'
# Loop over data
foreach($data as list($ID, $name)) {
    echo 'The ID: '.$ID.' is '.$name.'<br />';

You can now also handle non-scalar values as iterator keys meaning the element keys may not have values that are of string or integer value, which you'd of previously had to of implemented an Iterator class and called the 'keys()' method on the object.

If we missed something - let us know in the comments and we'll get it included!

Make your Instagram beautiful. Preview your images before you post them ›