PHP 7: New Features

PHP 7 was released on December 3rd, 2015 and has a lot of new features. I am going to explain the most important ones and, at the end of the article, you can find a list of links with the complete and official updated features.

PHP 7 New Features

New Operators

PHP 7 comes with two new operators. These operators can be found on several programming languages and are being added to PHP in its last version:

  • The spaceship or combined comparison operator <=>
    This operator that is already present in other programming languages is a comparison operator that, given the following code example:

    This operator will return

    • -1  if $x is smaller than $y
    • 0   if $x is equal to $y
    • 1   if $x is greater than $y
  • The null coalesce operator that simplify the process of setting a default value in a var if this var is not defined. For example, in PHP 5 we could have this piece of code:

    In PHP 7 we can make use of null coalesce operator and write the previous line of code with this equivalent:

Scalar Type Hints

PHP 7 has included type hint declarations of four types:  int, float, string and bool. And what does this mean? Type Hint Declarations are type declarations on function parameters. This declaration was already available for Objects, but not for scalar types. This way, the runtime engine can check if the parameters that has been received in the function call can be checked in order to see if the parameters of the type required.

We can activate or deactivate this parameter checking with a statement:

in the file where you want to allow scalar type hinting. You have more information here:

If you want to read all information about scalar types in PHP, you can find it in this page.

Anonymous Classes

In another languages like JavaScript, Java or C# you can declare anonymous functions that are used when you don’t need a new named and well documented class and you just need a class that will be used in a single place. The syntax to create an anonymous class is the following:

new class (arguments) {definition}

And this is an example:

 

Group Namespace Declarations

When we have to declare use This gives the ability to group multiple use declarations according to the parent namespace. This seeks to remove code verbosity when importing multiple classes, functions, or constants that come under the same namespace.

PHP 7 Performance

Here we can see an infographic created by Zend about the new PHP version performance:

PHP 7 Improvement Tests - Zend

PHP 7 Improvement Tests – Zend

Leave a Reply

Your e-mail address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.