+1 (506) 500-5957 sales@monovm.com Get US VPS for 50% OFF!

 PHP 8 Released: New Features in PHP 8!

PHP 8 has been officially announced and readily available to all users. PHP 8.0.0 marks the latest major update of the PHP language.

Posted: 28 Nov, 20 Updated: 14 Dec, 21 by Susith Nonis 7 Min

List of content you will read in this article:

PHP 8 has been officially announced and readily available to all users. PHP 8.0.0 marks the latest major update of the PHP language. This means that it comes with bigger changes and multitude of features and improvements. Update to the newest issue of PHP 8.0.0 from here.

PHP 8.0 comes with numerous improvements and new features such as:

  • Union Types
  • Named Arguments
  • Match Expressions
  • Attributes
  • Constructor Property Promotion
  • Nullsafe Operator
  • Weak Maps
  • Just In Time Compilation and more

With the new update comes quite some changes, and there’s a high chance that you will need to make some changes in your code to get it running on PHP 8. Don’t worry though, cause we have included all the deprecations in this post for your convenience.

Named Arguments

Named arguments allow you to pass in values to a function, by specifying the value name, so that you don't have to take their order into consideration. Support for Attributes has been added.

Here’s an example for named arguments:

In PHP 7:

htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);

In PHP 8:

htmlspecialchars($string, double_encode: false);

Instead of using PHPDoc annotations, with the new update you can use structured metadata with PHP’s native syntax.

Here’s an example for attributes:

In PHP 7:

class PostsController
{
    /**
     * @Route("/api/posts/{id}", methods={"GET"})
     */
    public function get($id) { /* ... */ }
}

In PHP 8:

class PostsController
{
    #[Route("/api/posts/{id}", methods: ["GET"])]
    public function get($id) { /* ... */ }
}

Constructor property promotion

Instead of specifying class properties and a constructor for them, PHP can now combine them into one.

Here’s an example for constructor property:

In 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;
  }
}

In PHP 8

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

Union Types

Instead of using PHPDoc annotations for a combination of types, with the new update you can use native union type declarations that are validated at runtime.

Here’s an example for union types:

In PHP 7

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

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

new Number('NaN'); // Ok

In PHP 8

class Number {
  public function __construct(
    private int|float $number
  ) {}
}

new Number('NaN'); // TypeError

Match Expression

The new match is similar to switch and has the following features:

  • Match is an expression, meaning its result can be stored in a variable or returned.
  • Match branches only support single-line expressions and do not need a break; statement.
  • Match does strict comparisons.

Here’s an example for match expression:

In PHP 7

switch (8.0) {
  case '8.0':
    $result = "Oh no!";
    break;
  case 8.0:
    $result = "This is what I expected";
    break;
}
echo $result;
//> Oh no!

In PHP 8

echo match (8.0) {
  '8.0' => "Oh no!",
  8.0 => "This is what I expected",
};
//> This is what I expected

Nullsafe operator

Instead of using null check conditions, you can now use a chain of calls with the new nullsafe operator. When the evaluation of one element in the chain fails, the execution of the entire chain aborts and the entire chain evaluates to null.

Here’s an example for the nullsafe operator:

In PHP 7

$country =  null;

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

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

In PHP 8

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

Saner string to number comparisons

When comparing to a numeric string, PHP 8 will use a number comparison. Otherwise, it will convert the number to a string and will use a string comparison.

Here’s an example:

In PHP 7

0 == 'foobar' // true

In PHP 8

0 == 'foobar' // false

Consistent type errors for internal functions

Most of the internal functions now throw an Error exception if the validation of the parameters fails.

In PHP 7:

strlen([]); // Warning: strlen() expects parameter 1 to be string, array given

array_chunk([], -1); // Warning: array_chunk(): Size parameter expected to be greater than 0

In PHP 8:

strlen([]); // TypeError: strlen(): Argument #1 ($str) must be of type string, array given

array_chunk([], -1); // ValueError: array_chunk(): Argument #2 ($length) must be greater than 0

Just-in-Time compilation (JIT)

PHP 8 introduces 2 JIT compilation engines. The JIT compiler comes with significant improvements with not always within the web request context. The two are JIT compilations are Tracing JIT and Function JIT. The tracing JIT shows about 3 times better performance and 1.5-2 times of improvements on some specific long-running applications.

  • There are stricter type checks in place for arithmetic/bitwise operators
  • Validations for abstract trait methods
  • Ensure correct signatures of magic methods
  • Reclassified engine warnings
  • Always generate fatal error for incompatible method signatures
  • The @ operator will no longer silence fatal errors
  • Remove inappropriate inheritance signature checks on private methods
  • You can explicitly declare type information for most function parameters, function returns, as well as class properties
  • Static return type
  • Adding internal function argument and return types
  • Opaque objects instead of resources for Curl, Gd, Sockets, OpenSSL, XMLWriter, and XML extensions
  • Allow a trailing comma in parameter lists RFC and closure use lists
  • Non capturing catches
  • Variable Syntax changes
  • Treats namespaced names as a single token
  • Alows ::class on objects

Also there are some new classes, interfaces and functions:

With the new update of PHP, it’s bound to have higher performance, better syntax and improved type safety. For more details you can visit the PHP official website.

If you liked this article, share it among your friends and let them know about the game changing update.

Susith Nonis

Susith Nonis

I'm fascinated by the IT world and how the 1's and 0's work. While I venture into the world of Technology, I try to share what I know in the simplest way with you. Not a fan of coffee, a travel addict, and a self-accredited 'master chef'.

user monovm

rajeshwari

2020, Dec, 20

Great one,This article provides the informative knowledge about PHP. Thanks for sharing.