Bureau of Programming

PHP 7 (and 7.1) in a Nutshell

If my day job is any indication, PHP won’t die. You can make the best of it by upgrading to the latest version. Here’s a rundown of the new features in PHP 7.0 and 7.1.

Constant arrays

Arrays can now be specified as constants using define:

define('BLACKHOLE_USER_IDS', [123, 456]);

Spaceship operator

The <=> operator lets you compare two expressions, and determine if one is less than, equal to, or greater than the other in a single operation:

1 <=> 1; // 0
1 <=> 2; // -1
2 <=> 1; // 1

Null coalescing operator

The ?? operator returns the second operand if the first is unset or null. This is useful for setting default values in the absence of some other value:

$latitude = $_GET['latitude'] ?? DEFAULT_LATITUDE;

Scalar and return type declarations

Parameter types and return types can be specified when defining functions:

function echoDate(\DateTime $date): void {
    echo $date->format('Y-m-d H:i:s');
}

function sumOfInts(int ...$ints): int {
    return array_sum($ints);
}

function getName(array $user): ?string {
    return $user['name'] ?? null;
}

The valid types are: a class or interface name, self, array, callabale, bool, float, int, string. (In PHP 7.1, you can also specify void and iterable. Additionally, the ? prefix indicates it may be of that type or null.) The implementation is much looser than strictly-typed languages; for example, you cannot specify a return type of an array of DateTime instances.

By default, PHP will coerce values of the wrong type into the expected scalar type if possible. In strict mode, if type coercion fails, it will throw a fatal error (TypeError).

Negative string offsets (PHP 7.1)

A single character can be retrieved from a string using a negative offset:

"abcdef"[-2] // e

Group use declarations

Previously, namespaces had to be written in their entirety:

use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

Now, classes in the same namespace can be imported jointly using braces:

use some\namespace\{ClassA, ClassB, ClassC as C};

CSPRNG functions

The standard library can now generate cryptographically secure pseudo-random bytes (random_bytes) and integers (random_int):

bin2hex(random_bytes(5)); // b78ef0476c
random_int(1, 5); // 5

Unicode codepoint escape syntax

Any Unicode codepoint can be specified in hexadecimal form:

"\u{1F355}" // 🍕

Multi catch exception handling (PHP 7.1)

Multiple exception types can be caught in a single block using pipes |:

try {
    // some code
} catch (NetworkException | FormatException $e) {
    // handle either kind of exception
}

Additional new features

Share on TwitterRead previous articleEmail the editor