PHP 8 has been officially released on 26th November 2020, this new update brings many optimizations and powerful features in this language. Interesting thing is that it will allow to write better code and build more strong applications.

Just in Time Compiler (JIT)

We all know that PHP is an interpreted language: it’s not compiled like java, C or Rust program. It’s translated to the machine code, the CPU understands it -> at runtime. It’s a technique, it will compile parts of the code at a time, so that the compiled can be used instead. Just like a cached version of interpreted program generated at runtime.

Flow of JIT

Just in Time Compiler (JIT)

PHP Array Starting Negative Index

In PHP, if the array starts with a negative index (index <0), the following indicators will start with 0 (more on this in the array_fill documentation).

Look at the following example:

$a = array_fill(-8, 5, true);
var_dump($a);

Result in PHP 7 Would be:

array(4) { [-5]=> bool(true) [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) }

Result in PHP 8 Would be:

array(4) { [-5]=> bool(true) [-4]=> bool(true) [-3]=> bool(true) [-2]=> bool(true) }

Throw Expression

In PHP, when discard is as a statement, it is not possible to use it in places where only expressions are allowed.

$callable = fn() => throw new Exception();

// $value is non-nullable.
$value = $nullableValue ?? throw new InvalidArgumentException();

// $value is truthy.
$value = $falsableValue ?: throw new InvalidArgumentException();

Allow ::class syntax on objects

To get the name of the class, we can use Foo \ Bar:: class syntax. PHP 8 allows us to extend the same syntax for objects therefore it is now possible to get the class name of a given object, as shown in the following example:

$object = new stdClass;
var_dump($object::class); // "stdClass"

$object = null;
var_dump($object::class); // TypeError

In PHP 8, $object::class provides the same result as get_class($object). If $object is not an object, it raises a TypeError exception.

Named Arguments

The name of the named argument parameter allows to pass arguments to the function based on the condition of the whether parameter.

We can also pass named arguments to a function by just simply adding the parameter name before its value:

Ex…

callFunction(name: $value);

In above example, the keywords can be used in reverse like this….

callFunction(array: $value);

Union Types 2.0

PHP is a dynamically typed structure, so union types are very useful in many places. Union types are a collection of two or more types that indicates which one of them can be used.

// In PHP 7.4
class Number {
   private $number;

   public function setNumber($number) {
      $this->number = $number;
   }
}

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

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