Some New Tips About PHP7

Some New Tips About PHP7

It's been several months that PHP 7 was released, and the latests frameworks already upgraded to be compatible with this version.

Laravel Homestead, the OOTB server environment is now up to date as well, so all your new projects will run on a PHP 7 server. In addtion to be radically faster (from 25% to 70%), you are now able to do some new cool stuff. Here are some of them:

The spaceship operator <=>

Because it looks like a spaceship!

It is basically a combination of <, > and ==

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

In $a <=> $b, if $a is less than $b than the result will be -1. If it's equal, the result will be 0. And if its greater than, the result will be 1.

Good way to remember it: in the same order of <=>, you get -1, 0, 1.

Null Coalesce Operator ??

When you want to access a variable, but if this variable is not set you want to set a default value, you would do something like that:

if (isset($_GET['username'])) {
     $username = $_GET['username'];
} else {
     $username = 'Mydnic';

// or this
$username = $_GET['username'] ? $_GET['username'] : 'Mydnic';

A bit of a overkill, right ? Well now you can simply do this:

$username = $_GET['username'] ?? 'Mydnic';

You just have to remember ?? which is kinda nice.

You can even chain it !

$username = $_GET['username'] ?? $_GET['post'] ?? 'Mydnic';

Isn't that just great ??

Group use declarations

I'm not a big fan of this one because I think this is quite ugly, but it's still nice to have in some occasions.

The purpose is to import more than one class from the same namespace with only one use declaration. Here's what it looks like:

// Before PHP 7
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;

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

Simpoly notice the brackets and you're good to go


Scalar Type Hinting

And finally, the most important...

If you are exclusively familiar with PHP, you probably wonder "what the heck is type hinting ?". Well it's pretty simple actually. The goal is to declare the type of your function parameters, and so return values that are of a specific type, which can be integer, string, boolean, float.

The main goal is to prevent programming mistakes, like unintentionally making calculation with strings and integer mixed up..

Now, type hinting was already allowed before, but it was restricted to classes, arrays and callables.It means you were able to do that:

// Before PHP 7
public function doSomething(array $arrayOfUsers) { // here "array" is a type hint
     // $arrayOfUsers is necessarily an array

In PHP 7 the Scalar Types (integers, strings, booleans, floats) can be used as type hints as well. It works like this:

function foo(): int {
    return 1;