What's New in PHP 8

PHP 8

PHP 8.0 is a major update of the PHP language. It contains many new features and optimizations including named arguments, union types, attributes, constructor property promotion, match expression, nullsafe operator, JIT, and improvements in the type system, error handling, and consistency.

PHP 8 has been officially released to the general availability on November 26, 2020!

Table of contents

  1. PHP JIT Compiler
  2. PHP 8 New Features
  3. PHP New Functions & Classes
  4. PHP 8 Performance

PHP JIT (Just in Time Compiler)

A JIT compiler runs after the program has started and compiles the code (usually bytecode or some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usually faster, typically the host CPU's native instruction set. A JIT has access to dynamic runtime information whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently. - StackOverflow answer by Mark Cidade

Tracing JIT, the most promising of the two, shows about 3 times better performance on synthetic benchmarks and 1.5–2 times improvement on some specific long-running applications.

So we can conclude that JIT Compiler is one of the most important updates. However, JIT is not enabled by default.

Zeev Surasky, co-author of the PHP JIT proposal, shows how much calculations would be faster with JIT:

PHP 8 New Features

Nullsafe operator

This Nullsafe operator introduces the nullsafe operator. The nullsafe operator provides functionality similar to null coalescing, but also supports method calls.

Instead of writing classic !== null you can use the “?” operator to write just 1 line of code. Instead of writing this:


 $country =  null;

 if ($session !== null) {

   $user = $session->user;

   if ($user !== null) {
  
     $address = $user->getAddress();

     if ($address !== null) {
    
       $country = $address->country;
     }
   }
 }

PHP 8 allows you to write this:

$country = $session?->user?->getAddress()?->country;

Nested nullsafe operators

It's possible to nest several nullsafe operator calls like so:

$foo?->bar?->baz()?->boo?->baa();

Constructor property promotion - RFC

Instead of specifying class properties and a constructor for them, PHP can now combine them into one. Less boilerplate code to define and initialize properties.


// PHP 7
class Point {
  public float $x;
  public float $y;
  public float $z;

  public function __construct(
    float $x = 0.0,
    float $y = 0.0,
    float $z = 0.0
  ) {
    $this->x = $x;
    $this->y = $y;
    $this->z = $z;
  }
}

// PHP 8
class Point {
  public function __construct(
    public float $x = 0.0,
    public float $y = 0.0,
    public float $z = 0.0,
  ) {}
}

Saner string to number comparisons

When comparing to a numeric string, PHP 8 uses a number comparison. Otherwise, it converts the number to a string and uses a string comparison.

PHP 8 introduces Saner string to number comparisons, aiming to make string to number comparisons more reasonable.

“This RFC intends to give string to number comparisons a more reasonable behavior: When comparing to a numeric string, use a number comparison (same as now). Otherwise, convert the number to string and use a string comparison.” - Nikita Popov


 // PHP 7

 0 == 'foobar' // true


 // PHP 8

 0 == 'foobar' // false

The following table compares the behavior of a string to a comparison of previous versions of PHP and numbers in PHP 8:


 Comparison    | Before | After
 ------------------------------
  0 == "0"     | true   | true
  0 == "0.0"   | true   | true
  0 == "foo"   | true   | false
  0 == ""      | true   | false
 42 == "   42" | true   | true
 42 == "42foo" | true   | false

Check out how string to number comparisons change in PHP 8 in the official RFC from Nikita Popov.

Union Types 2.0 RFC

  • Union Types 2.0 suggests using arbitary union types.
  • The syntax format is as simple as type1|type2|....
  • These can be used in all above mentioned places of type declarations.

A union type describes a value that can be one of several types. A “union type” accepts values of multiple different types, rather than a single one. This means if the programming language supports union types, you can declare a variable in multiple types. For instance, there can be a function which can accept variable of type “string” or “float” as a parameter.

When it comes to PHP, it already supports two special union types:

  • Type or null
  • array or Traversable, using the special iterable type.

PHP 7 does not currently support union types so coders have to use PHPDoc annotations as a workaround. In PHP 8 union types are coming to natively.


 // In PHP 7
 class Number {
     /**
      * @var int|float $number
      */
     private $number;

     /**
      * @param int|float $number
      */
     public function setNumber($number) {
         $this->number = $number;
     }

     /**
      * @return int|float
      */
     public function getNumber() {
         return $this->number;
     }
 }

After the PHP 8 update, union types are part of the native language. The above code can be written as follows:


 // In PHP 8
 class Number {
     private int|float $number;

     public function setNumber(int|float $number): void {
         $this->number = $number;
     }
 }

New Mixed type RFC

An explicit mixed type would allow people to add types to parameters, class properties and function returns to indicate that the type information wasn't forgotten about, it just can't be specified more precisely, or the programmer explicitly decided not to do so.

Since PHP 8.0, we can use a new mixed type. It is equivalent to the following union type:

array|bool|callable|int|float|null|object|resource|string

We can use mixed type anywhere types are accepted: parameters, return values, and properties.


 class Blog {
     public function title(string $title) {}
 }

 class Task extends Blog {
     // Parameter type was widened from int to mixed, this is allowed
     public function title(mixed $title) {}
 }
 

Match Expression RFC

Does match expression replace the switch?. The match can return values, doesn't require lengthy statements like a switch. It uses strict type comparison


 //The switch statement loosely compares (==) the given value to the case values. This can lead to some very surprising results.
 switch ('100') {
   case 100:
     $price = "Oh no!";
     break;
   case '100':
     $price = "This is what I expected";
     break;
 }
 echo $price;
 ///> Oh no!

 //The match expression uses strict comparison (===) instead. The comparison is strict regardless of strict_types.
 echo match ('100') {
   100 => "Oh no!",
   '100' => "This is what I expected",
 };
 

PHP New Functions & Classes

There have been a lot of new functions and classes in the PHP 8. You can also view a list of new updates on the official PHP website.

  • Weak Map class RFC
  • Attributes v2 RFC
  • Throw Expression RFC
  • Trailing Comma in Parameter List.
  • Inheritance with private methods RFC
  • Arrays Starting With a Negative Index.
  • Non-capturing catches RFC

PHP 8 Performance

With the PHP 7 version, there were big changes in speed compared to previous PHP versions. According of the most tests PHP 8.0 is almost 30% faster than PHP 7.4. Check Kinsta.com PHP benchmarks and PHP 8 vs PHP 7.4, PHP7.3 performance articles.

There is also a nice site called "PHP Benchmarks".

Summary

What an interesting improvement and a new features in PHP 8, I hope you really enjoyed this article and it was useful to you.


If you like this blog post and it was useful to you, please follow us on Twitter and Facebook.



Related articles

Sources:

Post a Comment

0 Comments