DEV Community

Cover image for 3 essential new features of PHP 8
Valeriu Guțu
Valeriu Guțu

Posted on

3 essential new features of PHP 8

Constructor Property Promotion

This new feature allows developers to define class properties directly within the constructor method, without having to declare them separately at the top of the class. This can make the code more concise and readable, as well as reduce the amount of duplicated code.

In previous version of PHP, you would have to declare the properties at the top of the class, and then set the value of the properties in the constructor.

class Example {
    private string $name;
    private int $age;
    private bool $isActive;
    public function __construct(string $name, int $age, bool $isActive = true) {
        $this->name = $name;
        $this->age = $age;
        $this->isActive = $isActive;
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, the code from above can change to

class Example {
    public function __construct(
        private string $name,
        private int $age,
        private bool $isActive = true
    ) {}

    // ... other class methods ...
}

$example = new Example('John', 25);
Enter fullscreen mode Exit fullscreen mode

Union Types

In PHP 8, union types allow for specifying multiple types for a function or method parameter or return type. This allows for more specific type checking, and can help prevent errors caused by passing the wrong type of argument to a function. For example, a function that accepts either a string or an integer for a parameter could be declared like this:

function example(int|string $param) {
    // function body
}
Enter fullscreen mode Exit fullscreen mode

This means that the example function accepts either a string or an integer as the value of $param.

Note that Union types are not supported for class and interface types, and also if you use the mixed type, the union types will be ignored.

Match Expressions

Match expressions in PHP 8 provide a more concise and expressive way to perform pattern matching, as it allows checking the type of variable and perform different actions based on the type. For example, instead of writing an if-else or switch statement, you can use a match expression like this:

$message = match ($statusCode) {
    200, 300 => null,
    400 => 'not found',
    500 => 'server error',
    default => 'unknown status code',
};
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are many new features and improvements in PHP 8. You can go over all of them here.

Top comments (1)

Collapse
 
bn_geek profile image
Mohcin Bounouara

Thank you for your post!