PHP 7.1 was released at the end of 2016 and web servers are being upgraded to support the latest additions to the language. This is a good moment for developers to see what new features have been added to PHP in the newest version.
Void Return Type
Let’s start with something small and simple. PHP already has support for function return types, excluding the void data type. A void return type means that no value is returned from a function. In version 7.1, you can indicate this in the function signature by using the typical colon syntax that already works with other return types: protected function foo(string $value): void {}.
Nullable Types
PHP also already has support for type declarations in function parameters. However, if you specify that a parameter must be a string, you cannot pass null to the function for that parameter slot. The same applies to return types: if a function is set to return an integer, it cannot return null.
Starting from PHP 7.1, functions support nullable types as parameters and return values. This means that you can use a question mark in front of a type declaration. For example, the following function can accept as well as return a value of null: public function multiply (?int $number): ?int { return $number * 2 }.
Catching Multiple Exceptions
Another great addition to PHP 7.1 is the ability to catch multiple exceptions at once. In the past, you have had to use multiple catch blocks even if they catch the exception in an identical way. From now on, you can use the OR operator (“|”) to make your code reuse the same exception handling logic for multiple exception types. Here’s how it works: catch (AnException | AnotherException $e) {}. This must of course be used with a try block.
Visibility Modifiers for Constants
Modifying the visibility of methods and properties using the private, protected and public keywords has been possible for a long time. Constants on the other hand have always been public and it has not been possible to change this. In PHP 7.1, constants have the same three visibility modifiers as methods and classes and they work just as you would expect. For example, to create a private constant, you can use: private const POSTS_PER_PAGE = 10.
For backward compatibility, it is not required to give a constant any visibility modifier. All constants without an explicitly set visibility default to public.
In addition to the changes covered here, PHP 7.1 contains over 20 more changes and improvements. A complete list of the changes can be found in the PHP wiki at wiki.php.net.
No comments yet (leave a comment)