PHP 7 cool new features

Hello all,

Today, I thought to give you a quick run through about cool new features in PHP 7. PHP 7 has been there for sometime but it is still worth paying some closer look at what it has to offer to the world of PHP development. In this post I will be giving few examples which are exclusively to PHP 7 and onwards. Please note that at the time I write this post PHP 7.2.5 is available to download.

Scalar type declarations

Type declaration tells the type of the arguments needs to be passed when calling a function. Available scalar types are class, self, callable, array, int, string, float, boolean and iterable. (The latter five was introduced as part of PHP 7).

declare(strict_types=1);
function getTotal(int ...$ints)
{
return array_sum($ints);
}

var_dump(getTotal(45, 85, 134));

The above will give you this,

int(264)

With the strict_types enabled if you call the same function by passing mixed type parameters like this,

var_dump(getTotal("45", '8', 134.4));

This will give you a TypeError,

Fatal error: Uncaught TypeError: Argument 1 passed to getTotal() must be of the type integer, string given, Next TypeError: Argument 2 passed to getTotal() must be of the type integer, string given, Next TypeError: Argument 3 passed to getTotal() must be of the type integer, float given. 

For additional information, the declaration of strict type is per file basis and it will affect function parameter types as well as function return types. Continue reading

Share