What’s New in PHP 8 (Features & Improvements)

Date:

What’s New in PHP 8 (Features & Improvements) – it 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.

As PHP 8 is still under development, we could see several changes before the final release. We’ll keep track of these changes and update this post regularly, so make sure you don’t miss anything about PHP 8 and check this post again from time to time.

So, what features and improvements should we expect with PHP 8? What’s the biggest thing coming with PHP 8, the next major release of the language?

What’s New in PHP 8 (Features & Improvements)

Major New Features

  • Named Arguments
  • Attributes
  • Constructor Properties
  • Just-In-Time Compilation
  • Union Types
  • Null-safe Operator
  • match expressions
  • Consistent type errors for internal functions

Named Arguments

Named arguments allow passing arguments to a function based on the parameter name, rather than the parameter position. This makes the meaning of the argument self-documenting, makes the arguments order-independent, and allows skipping default values arbitrarily.

PHP 7

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

PHP 8

htmlspecialchars($string, double_encode: false);

Attributes

Attributes as a form of structured, syntactic metadata to declarations of classes, properties, functions, methods, parameters and constants. Attributes allow to define configuration directives directly embedded with the declaration of that code.

Similar concepts exist in other languages named Annotations in Java, Attributes in C#, C++, Rust, Hack and Decorators in Python, Javascript.

So far PHP only offers an unstructured form of such metadata: doc-comments. But doc-comments are just strings and to keep some structured information, the @-based pseudo-language was invented inside them by various PHP sub-communities.

On top of userland use-cases there are many use-cases for attributes in the engine and extensions that could affect compilation, diagnostics, code-generation, runtime behavior and more. Examples are given below.

The wide spread use of userland doc-comment parsing shows that this is a highly demanded feature by the community.

PHP 7

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

PHP 8

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

Constructor Properties

Currently, the definition of simple value objects requires a lot of boilerplate, because all properties need to be repeated at least four times. Consider the following simple class:

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,
  ) {}
}

Just-In-Time Compilation

PHP 8 introduces two JIT compilation engines. 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. Typical application performance is on par with PHP 7.4.

Image from php.net

Union Types (V2.0)

A “union type” accepts values of multiple different types, rather than a single one. PHP already supports two special union types:

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

However, arbitrary union types are currently not supported by the language. Instead, phpdoc annotations have to be used, such as in the following example:

PHP 7

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

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

new Number('NaN'); // Ok

PHP 8

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

new Number(‘NaN’); // TypeError

Null-safe Operator

Proposes the new nullsafe operator ?-> with full short circuiting.

PHP 7

$country =  null;

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

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

PHP 8

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

Match expression

Proposes adding a new match expression that is similar to switch but with safer semantics and the ability to return values.

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!

PHP 8

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

Consistent type errors for internal functions

For user-defined functions, passing a parameter of illegal type results in a TypeError. For internal functions, the behavior depends on multiple factors, but the default is to throw a warning and return null. This RFC proposes to consistently generate TypeError exceptions for all invalid parameter types, regardless of whether the function is user-defined or extension-defined.

First, a detailed description of the current behavior is in order. For user functions parameters of invalid type always result in a TypeError, regardless of strict_types option:

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

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

You can read more on php.net

You may also like How to Run Multiple PHP Versions with Apache on Ubuntu

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Share post:

Subscribe

Popular

More like this
Related

How to Protect WordPress with Cloudflare

Cloudflare, Inc. is an American content delivery network and...

Facebook Outage

Mike Schroepfer - CTO @ Facebook. *Sincere* apologies to everyone...

Magento 2 One Page Checkout (One Step Checkout)

Magento 2 One Page Checkout - One Page checkout...