PHP 7.1 Features

php-logo-Converted-01-3

PHP 7.0 has been out for a while. In this time we have detected some things that seems needed in order to continue typing and improving the speed of PHP. That’s why we have now PHP 7.1

Nullable types

The first and major change. Nullable types, now all the variables typed in all functions or returns can be also supported as null if we specify it in the declaration with a “?” question mark.


function answer(): ?int {
    return null; //ok
}

function answer(): ?int {
    return 42; // ok
}

function answer(): ?int {
    return new stdclass(); // error
}

Also you can declare null parameteres on the function arguments


function say(?string $msg) {
  if ($msg) {
    echo $msg;
  }
}
 
say('hello'); // ok -- prints hello
say(null); // ok -- does not print
say(); // error -- missing parameter
say(new stdclass); //error -- bad type

Return Void

After the previous typed functions, we are getting used to type all the possible functions in the code. So what happens if a function doesn’t return anything. Now we can also type them. So basically no function in PHP 7.1 should not have a return type.

Example:

function should_return_nothing(): void {
    return; // Valid
function returns_one(): void {
    return 1; // Fatal error: A void function must not return a value
}

// Of course if your don't use return is also valid.

Class constant Visibility

Now it’s possible to give private or protected visibility to a constant in the class. Previously only public was permitted.

<?php
class ConstDemo
{
    const PUBLIC_CONST_A = 1;
    public const PUBLIC_CONST_B = 2;
    protected const PROTECTED_CONST = 3;
    private const PRIVATE_CONST = 4;
}

Others

There are some more features, you can find them all at Official PHP 7.1 new features