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 ==

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:

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

Originally published at