PHP 8 Features and Improvements

In this article, we will see PHP 8 Features and improvements. PHP 8 was released in November 2020 and it is a new major version of PHP. There are some breaking changes and lots of new PHP 8 features and performance improvements.

Currently, the latest version is PHP 8.1 and which was released on November 25, 2021, and It included several improvements, such as enumerations (also called “enums”), readonly properties, and array unpacking with string keys.

PHP 8 Features

See below for new PHP 8 features

1). Union Types

Union types are a collection of two or more types that indicate that either can be used. This will also allow several types to be defined for the arguments received by a function, as well as for the value it returns.

Note that void can never be part of a union type since it indicates “no return value at all”. Furthermore, nullable unions can be written using |null, or by using the existing? notation.

It is one of the good features from a list of PHP 8 features.

See below example of PHP version 8 where how union type is used:

// In PHP Version 7.4
class Digit {
    private $digit;
    public function setDigit($digit) {
        $this->digit = $digit;
    }
}

// In PHP Version 8
class Digit {
    private int|float $digit;
    public function setDigit(int|float $digit): void {
        $this->digit = $digit;
    }
}

2). JIT Compiler

When PHP code is run, it’s usually done by compiling & executed in a virtual machine. JIT will change this by compiling the code into x86 machine code and then running that code directly on the CPU.

PHP Opcache supports JIT. It’s disabled by default, and if enabled, JIT compiles and caches native instructions. It does not make a noticeable difference in IO-bound web applications but provides a performance boost for CPU-heavy applications.

It is one of the new features from a list of PHP 8 features.

# Enabling JIT in php.ini
opcache.enable=1
opcache.jit_buffer_size=100M
opcache.jit=tracing

3). Nullsafe Operator

Instead of writing classic !== null you can use the “?” operator to write just reduce multiple lines of code to a single line.

The Nullsafe operator is similar to the ternary operator but will behave like an isset on the left-hand operand instead of just using its boolean value. This makes this operator especially useful for arrays and assigning defaults when a variable is not set.

It is not fully reliable as it doesn’t work on method calls. Instead, you need intermediate checks, or rely on optional helpers provided by some frameworks:

It is one of the good features from a list of PHP 8 features.

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

With the addition of the null safe operator, we can now have null coalescing-like behaviour on methods.

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

4). Named Arguments

Named arguments allow you to pass in values to a function, by specifying the value name, so you don’t need to consider their order, also you can also skip optional parameters!

It is one of the good features from a list of PHP 8 features.

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

5). Attributes 

Attributes allow us to declare meta-data for our functions, classes, properties, and parameters. It map to PHP class names (declared with an Attribute itself), and they can be fetched programmatically with PHP Reflection API.

It is one of the good features from a list of PHP 8 features.

Attributes syntax is very simple, attributes which are also called annotations are specially formatted text enclosed with “<<” and “>>.”

#[CustomAttribute]
class Foo {
#[AnotherAttribute(42)]
public function bar(): void {}
}

This allows us to easily declare attributes/annotations which previously required storing them in doc block elements and parsing the string to infer them.

6). Inheritance with private methods

Earlier, PHP used public, protected, and private methods to apply the same inheritance checks. In other words, the same method signature rules as the protected and public methods should be followed by private methods. Because of this, children’s classes would not be able to use private methods.

It is one of the good features from a list of PHP 8 features.

This updated PHP 8 feature has modified the behavior, so these inheritance checks are no longer performed on private methods. In addition, it did not make sense to use the final private feature, so doing so would now cause a warning:

Warning: Private methods cannot be final as other classes never override them

7). Match Expression

The new match expression is a terser safer alternative to the well-known switch. It does not require the use of case and break statements support combined conditions and return a value instead of entering a new code block.

It is one of the good features from a list of PHP 8 features.

Here’s a typical PHP 7 switch:

switch (1) {
	case 0:
		$result = 'Foo';
		break;
	case 1:
		$result = 'Bar';
		break;
	case 2:
		$result = 'Baz';
		break;
}
 
echo $result;
//> Bar

And, here’s how the same code could look with PHP 8:

echo match (1) {
	0 => 'Foo',
	1 => 'Bar',
	2 => 'Baz',
};
//> Bar

8). Weak Maps

A weak map is a collection of data (objects) in which keys are weakly referenced, meaning that they are not prevented from being garbage collected.

It is one of the good features from a list of PHP 8 features.

WeakMaps and WeakRefs can be used to delete objects when only the cache references the entity classes of the objects. This leads to resource-saving handling of the objects.

See the below example:

$map = new WeakMap;
$obj = new stdClass;
$map[$obj] = 42;
var_dump($map);

In long-run processes, this can prevent memory leaks, which eventually improve performance.

9). Constructor Property Promotion

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

// In php 7 or later minor version
class Shape {
    protected float $a;
    protected float $b;
    protected float $c;

    public function __construct(
        float $a = 0.0,
        float $b = 0.0,
        float $c = 0.0,
    ) {
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;
    }
}

// In PHP 8 version
class Shape {
    public function __construct(
        protected float $a = 0.0,
        protected float $b = 0.0,
        protected float $c = 0.0,
    ) {}
}

10). Consistent type error for internal functions

PHP will already throw TypeError in User-defined functions,  but internal functions rather emitted warnings and returned null. As of PHP 8, the behavior of internal functions has been made consistent.

 

Also, there are some new functions introduced in PHP 8. See below

1). str_contains() function

PHP 8 introduces str_contains(), which returns a simple boolean indicating if the needle is present in the haystack. It helps you to determine whether the given sub-string is present inside the string.

It is one of the new features from a list of PHP 8 features.

So instead of doing this:

if (strpos('string with lots of words', 'words') !== false) { /* … */ }

You would now do this:

if (str_contains('string with lots of words', 'words')) { /* … */ }

2). str_starts_with() and str_ends_with() functions

These functions are now incorporated into the core:

str_starts_with('haystack', 'hay'); // true
str_ends_with('haystack', 'stack'); // true

3). fdiv() function

The new fdiv() function does something similar as the fmod() and intdiv() functions, which allows for division by 0. Instead of errors, you’ll get INF, -INF or NAN, depending on the cas

4). get_debug_type() function

The function get_debug_type() returns the type of a variable. get_debug_type() returns more useful output for arrays, strings, anonymous classes and objects. Sure it sounds like gettype() but there are benefits of the later.

For example: calling gettype() on a class \Foo\Bar would return object. Using get_debug_type() will return the class name.

5). get_resource_id()

Resources are special variables in PHP, referring to external resources. One example is a MySQL connection, and another one is a filehandle.

Each one of those resources gets assigned an ID, though previously the only way to know that id was to cast the resource to int:

$resourceId = (int) $resource;

PHP 8 adds the get_resource_id() functions, making this operation more obvious and type-safe:

$resourceId = get_resource_id($resource);

 

PHP 8 features introduces a powerful lineup of features that elevate the development experience, making it easier to write cleaner, more efficient, and more expressive code. From the performance boost of JIT compilation to the improved error handling and the flexibility of union types and named arguments, PHP 8 empowers developers to create robust and future-proof web applications.

By embracing these keywords – JIT compilation, union types, match expressions, named arguments, constructor property promotion, error handling improvements, and attributes – developers can harness the full potential of PHP 8 and stay at the forefront of modern web development. Upgrade to PHP 8 and unlock a new level of efficiency, readability, and performance in your code. The future of PHP development starts with PHP 8!

I hope this article helps you to know PHP 8 features!