7 Favourite New Features of PHP 7

PHP 7 is now just around the corner. RC4 came out this week and there are only 2 more RCs before the final release on November 12th.

It comes with a whole bag of performance enhancements and new language features (as well as old langugae features being removed). I thought I would list out some of my favourite new additions.

1) <=> The Spaceship Operator

This operator returns -1 if the left operand is smaller, 0 if they are are equal and 1 if the right one is smaller. For example:

7 <=> 9; //returns -1
7 <=> 7; //returns 0
9 <=> 7; // returns 1

You can see that it is much cleaner and easier to check than to do the 3 conditions seperately that you have to do at the moment.

2) ?? Null Coalesce Operator

I really like this feature (although not sure about the name). Imagine the following example:

 $var = 0;
 if (isset($array['value']) && !is_null(isset($array['value'])) {
     $var = $array['value'];
 } else {
     $var = 8;
 }

Everyone knows that I am not a fan of single line if statements, but this, at the moment, could be rewritten as:

$var = (isset($array['value']) && !is_null(isset($array['value']))?$array['value']:8;

Urgh!

Well, with PHP 7's new ?? operator, we can make it less 'urgh':

$var = $array['value'] ?? 8;

It checks the value on the left is set AND is not Null then sets the variable to that. Otherwise, it sets the variable to the value on the right. How easy is that?!

And yes, it can even be chained:

$var = $array['value'] ?? $array['value2'] ?? 8;
3) Scaler Type Hinting

Up to now (well since PHP 5), you have been able to specify what object type a parameter being passed into a function should be. For example:

 public function myFunction (Car $var1, array $var2){}

The above declaration forces the first argument to be a Car object (or a subclass; or if Car is an interface, a class that implements it) and the second argument must be an array (supported since 5.1).

If you wanted to force parameters to be other scaler types (such as string, boolean or integer), you would have to manually check yourself within the function and produce the error yourself.

Well not anymore. In PHP 7, you can now declare parameters to be string, boolean, int or float. If you have 'strict typing' turned on, it will produce errors if you do not comply.

public function myFunction (Car $var1, array $var2, $var3)
{
    if (!is_string($var3) {
        throw new Exception ('Arguement 3 needs to be a string');
    }
    //continue with the rest of the function
}

Becomes:

public function myFunction (Car $var1, array $var2, string $var3)
{
    //continue with the rest of the function
}
4) Scaler Return Types

Whilst we are talking about functions and types. In PHP 7 you can now specify the return type of a function. This allows for better type hinting and prevents unexpected values from being returned.

Yes, the language famous for being 'loosely typed' has introduced ways to be more tightly typed.

The use is simple:

public function myFunction (Car $var1, array $var2, string $var3) : string
{
    //continue with the rest of the function
}

My function now has to return a 'string'.

There is one potential pitfall here. You can not return NULL if you declare a type. This is intentional as it aligns with the parameter behaviour and goes against the point of having a return type.

There is a future rfc that was missed in 7.0 but will probably be in 7.1 that addesses this problem as well as the problem of having to put $param = null in the argument list.

5) Declare Constant Arrays Using Define

As of 5.6, you were able to declare arrays in constants like so:

 const ARRAY = array(1,2,3,4);

Well in 7, you can now do it in the define function:

 define('ARRAY', [1,2,3,4]);

A small addition, but a useful one nonetheless.

6) Anonymous Classes

An interesting new addition is the ability to declare anonymous classes. PHP already supported anonymous functions but this allows you to make simple classes without having to hit the autoloader.

The keywords are new class.

Declaration would be like:

  public function getNewClass($param)
  {
       return new class($param) {
             private $i;
             public function __construct($param)
             {
                 $i = $param;
             }

             public function getVar()
             {
                 return $this->i;
             }
       };
  }

Then if I use the above function:

  $class = $this->getNewClass(7);
  echo $class->getVar(); //This would print '7'

Your anonymous classes can also extend classes and implement interfaces.

7) Performance Gains

Whilst it is really a behind the scenes feature, you can not talk about PHP 7 without talking about how much faster it is! Thanks to the PHPNG project led by Zend. And according to Zend (backed up by multiple other people who have benchmarked it), PHP 7 is twice as fast as 5.6 (which itself is much faster than 5.3 and below).

It has also overtaken HHVM on requests per second in many of the frameworks and use cases.

What are you still doing here? Go and try it out!

So as you can see, PHP 7 is going to be an exciting release! I have only touched upon what you can do with these features. You an try out all these right now (although not recommended for production servers) and it is 5 and half weeks before the final release!


© 2012-2017