loading...
Cover image for PHP 7 can do that ?

PHP 7 can do that ?

jmau111 profile image Julien Maury Originally published at blog.julien-maury.dev Updated on ・2 min read

PHP 7 has significantly improved overall performance. Indeed there are major features such as null coalescing operator or return type declarations. You should definitely check PHP documentation if you do not know them.

Here are less known features that might be useful.

Same namespace, same use

Before PHP 7 developers used to do :

use Universe\Saiyan;
use Universe\SuperSaiyan;
Enter fullscreen mode Exit fullscreen mode

Since PHP 7 :

use Universe\{Saiyan, SuperSaiyan};
Enter fullscreen mode Exit fullscreen mode

It's the same for functions and constants. You can group them if they belong to the same namespace.

Constants can be arrays

define('NAMES', [
    'first'  => 'John',
    'middle' => 'Fitzgerald',
    'last'   => 'Kennedy'
]);

echo NAMES['last']; //displays "Kennedy"
Enter fullscreen mode Exit fullscreen mode

Spaceship Operator

It's written like that <=>. It combines comparisons. It stands for " less than, equal to or greater than". It's really useful when using user-defined comparison functions to sort arrays because of the return values :

  • 0 if values are equal
  • 1 if value on the left is greater
  • -1 if the value on the right is greater

source

So let's sort the following array of actresses :

$actressesWithAcademyAwards = [
    [ 'name' => 'Katharine Hepburn', 'awards' => 4 ],
    [ 'name' => 'Jessica Lange', 'awards' => 2 ],
    [ 'name' => 'Meryl Streep', 'awards' => 3 ],
    [ 'name' => 'Cate Blanchett', 'awards' => 2 ],
];
Enter fullscreen mode Exit fullscreen mode

Instead of writing multiple lines to make the comparisons you can do it in 1 line :

usort($actressesWithAcademyAwards, function ($a, $b) {
    return $a['awards'] <=> $b['awards'];
});

print_r($actressesWithAcademyAwards);
Enter fullscreen mode Exit fullscreen mode

this returns :

Array
(
    [0] => Array
        (
            [name] => Jessica Lange
            [awards] => 2
        )

    [1] => Array
        (
            [name] => Cate Blanchett
            [awards] => 2
        )

    [2] => Array
        (
            [name] => Meryl Streep
            [awards] => 3
        )

    [3] => Array
        (
            [name] => Katharine Hepburn
            [awards] => 4
        )
)
Enter fullscreen mode Exit fullscreen mode

It's a very common PHP routine so the spaceship operator saves time. Besides it's more readable imho.

First / last key of array (PHP 7.3)

Since PHP 7.3 you can easily get the first and the last key of an array :

$array = [ 'v' => 1, 'i' => 2, 'p' => 3 ];

$firstKey = array_key_first($array);
$lastKey = array_key_last($array);

print_r($firstKey); // v
print_r($lastKey); // p
Enter fullscreen mode Exit fullscreen mode

Really clean because it does not affect the internal array pointer.

Spread operator in array (PHP 7.4)

This feature allows the following :

$abc = range('a', 'c');
$def = range('d', 'f');
$ghi = range('g', 'i');
$all = [...$abc, ...$def, ...$ghi, 'j'];
print_r($all);
Enter fullscreen mode Exit fullscreen mode

you get :

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
    [6] => g
    [7] => h
    [8] => i
    [9] => j
)
Enter fullscreen mode Exit fullscreen mode

It basically replaces array_merge() in most cases.

Arrow functions (PHP 7.4)

Be careful, for now it's meant for short closures with only one expression (hence the word "short") :

$c = 3;
$addC = fn($x) => $x + $c;
echo $addC(70); // 73
Enter fullscreen mode Exit fullscreen mode

No need for use keyword.

source

Constant visibility (PHP7.1)

class Mother {
    private const ERROR_LEVEL_1 = 'achtung';
}
Enter fullscreen mode Exit fullscreen mode

Visibility is useful to make sure things that should not be overwritten aren’t. Before PHP 7.1 this was not possible for class constants (always public).

source

Wrap up

PHP 7 is powerful. It's faster and it comes with great features. Did you know all these stuffs PHP 7 can do ?

Discussion

pic
Editor guide
Collapse
zexias profile image
Matheus Faustino
  • Arrow functions is really similar to lambda function from python.
  • Constant visibility is important from an OOP scenario
  • And the namespace thing is good, but it would be better if it was possible to use in any part of the namespace

EDIT: php 7 is a fantastic released

Collapse
bpedroza profile image
Bryan

I've never seen that namespace trick. Thanks for sharing!

Collapse
lokidev profile image
LokiDev

Keep in mind, that arrays with named keys cannot be unpacked :/.

$arrayOne = ['a' => 123];
$arrayTwo = [...$arrayOne];  // throws PHP Error!

Other than that: very useful :)

Collapse
igcp profile image
Igor Conde

Very good, I never really knew about this Namespace tip, thanks