PHP 7 – the new features at a glance – Part 1

PHP 7 is on everyone's lips and come with a number of syntactic enhancements and new features. In the future, PHP applications are not only faster, but the Java-language syntax approach further. Finally, you can set, which data types of functions in and which should come out again (Parameter type declarations and return type declarations), Thus the maintainability of the code can be improved.

Parameter type declarations and return type declarations

In PHP >= 5.3. was it previously possible function parameters, an input to assign an object type variable, the function expected, to generate other programmers that use the function to make it easier to document and an exception, When an object of a different type is used:

function test(MyObject $myObject){}

With PHP 7 can now also scalar types are used as input parameters:

function test(int $myObject){}

As also the erwrtete output of the function can be associated a type:

function test(int $myObject) : int{ 
return myObject

Scalar date types are:

  • strings (string)
  • integers (int)
  • floating point numbers (float)
  • Booleans (bool)

In addition (not scalar)

  • array
  • callables

With the help of the directive


, which can be used at the beginning of a file, the strict mode is enabled, of both the type checking the input and the output of functions affected.

Example strict mode

function test(string $int) : int{
    $int = $int + 1;
    return $int ;

1. With strict mode enabled at the beginning of the file, an exception is thrown:


Type error: Argument 1 passed to test() must be of the type string, integer given

2. Is accepted without exception the code runs without strict mode, Bsp::


Zero coalesce operator ??

The operator further shorten the cumbersome duplication in the syntax and is super convenient.

// Pre PHP 7 code
$var = isset($_GET['foo']) ? $_GET['foo'] : 'bar';

// PHP 7+ code
$var = $_GET['foo'] ?? 'bar';

Deserialization of objects using a White List

// converts all objects into __PHP_Incomplete_Class object except those of MyClass and MyClass2
$data = unserialize($foo, ["allowed_classes" => ["MyClass", "MyClass2"]);


Proceed to PHP 7 – the new features at a glance – Part 2