PHP 8.1 updates you must know

Posted on January 13, 2022
PHP

PHP 8.1 is a major update of the PHP language. It contains many new features, including enums, readonly properties, first-class callable syntax, fibers, intersection types, performance improvements and more.

 

Enumerations

PHP < 8.1
class Status
{
    const DRAFT = 'draft';
    const PUBLISHED = 'published';
    const ARCHIVED = 'archived';
}
function acceptStatus(string $status) {...}
PHP 8.1
enum Status
{
    case Draft;
    case Published;
    case Archived;
}
function acceptStatus(Status $status) {...}

 

Readonly Properties

PHP < 8.1
class BlogData
{
    private Status $status;
  
    public function __construct(Status $status)
    {
        $this->status = $status;
    }
   
    public function getStatus(): Status
    {
        return $this->status;   
    }
}
PHP 8.1
class BlogData
{
    public readonly Status $status;
  
    public function __construct(Status $status)
    {
        $this->status = $status;
    }
}

Readonly properties cannot be changed after initialization, i.e. after a value is assigned to them.
They are a great way to model value objects and data-transfer objects.

 

Never return type

PHP < 8.1
function redirect(string $uri) {
    header('Location: ' . $uri);
    exit();
}

function redirectToLoginPage() {
    redirect('/login');
    echo 'Hello'; // <- dead code
}
PHP 8.1
function redirect(string $uri): never {
    header('Location: ' . $uri);
    exit();
}

function redirectToLoginPage(): never {
    redirect('/login');
    echo 'Hello'; // <- dead code detected by static analysis
}

 

A function or method declared with the never type indicates that it will not return a value and will either throw an exception or end the script’s execution with a call of die(), exit(), trigger_error(), or something similar.

 

Final class constants

It is possible to declare final class constants, so that they cannot be overridden in child classes.

PHP < 8.1

class Foo
{
    public const XX = "foo";
}

class Bar extends Foo
{
    public const XX = "bar"; // No error
}
PHP 8.1

class Foo
{
    final public const XX = "foo";
}

class Bar extends Foo
{
    public const XX = "bar"; // Fatal error
}

 

PHP 8.1 assures better performance, better syntax, improved type safety. For more updates please visit PHP official site.

Search