PHP 8 - new features: part 1

Loaded with new features, performance improvements and breaking changes, all new PHP 8 is a major version that was released on November 26, 2020. Let’s start with all the new features which are very handy...


Union types

Since, the nature of PHP is dynamically typed, there are lots of places where they can be useful. Union types are a collection of two or more types which indicate that either one of those can be used.

Example: public function foo(Foo|Bar $input): int|float;

Note:

“void” can never be a part of the union type. Furthermore, “nullable” unions can be written using “|null” or by using the existing ? notation.

Example:

public function foo(Foo|null $foo): void;

public function bar(?Bar $bar): void;

JIT

The JIT (just-in-time) compiler provides significant performance improvements, although not always within the context of web requests. It opens the door for PHP to be used as a very performant language outside of the web, like fractal calculations.

The nullsafe operator

The nullsafe operator overcomes the shortcomings faced due to the null coalescing operator, such as not being able to work on method calls. With the addition of the nullsafe operator, we can now have null coalescing-like behaviour on methods like the one below:

$dateAsString = $booking->getStartDate()?->asDateTimeString();

Named arguments

Named arguments allow you to pass values to a function, by specifying the value name, so that you don't have to take their order into consideration, and you can also skip optional parameters.

Example:

function foo(string $a, string $b, ?string $c = null, ?string $d = null) { /* … */ }

foo( b: 'value b', a: 'value a', d: 'value d', );

Did you like our works?

We are known for Website Development and Website Designing, along with Android iOS application development in Mumbai, India. Please write us what you think, we would like to hear it from you

1