PHP 8.1.0 was officially released

PHP 8.1.0 has been released, which has brought many improvements and new features.

enumeration

Use enumeration instead of a set of constants and validate immediately.

enum Status
{
    case draft;
    case published;
    case archived;

    public function color(): string
    {
        return match($this)
        {
            Status::draft => 'grey',
            Status::published => 'green',
            Status::archived => 'red',
        };
    }
} 

Read only attribute

Read only properties cannot be changed after initialization, for example, after assigning values to them. They can be used to model value objects and data transfer objects.

class PostData
{
    public function __construct(
        public readonly string $title,
        public readonly string $author,
        public readonly string $body,
        public readonly DateTimeImmutable $createdAt,
        public readonly PostState $state,

    ) {}

}

First class callable syntax

You can now get a reference to any function.

function foo(int $a, int $b) { /* ... */ }
$foo = foo(...);
$foo(a: 1, b: 2);

New initializer

Object can now be used as default parameter values, static variables and global constants, as well as attribute parameters, which effectively makes it possible to use nested attributes.

class PostStateMachine
{
    public function __construct(
       private State $state = new Draft(),

    ) {

    }
}

Pure intersection type

When a value needs to satisfy multiple type constraints at the same time, the intersection type is used. Note that at present, intersection and union types cannot be mixed together, such as a & b|c.

function generateSlug(HasTitle&HasId $post) {
    return strtolower($post->getTitle()) . $post->getId();
}

Never return type

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

function dd(mixed $input): never
{
    // dump 
    exit;
}

never differs from void in that void still allows the program to continue. This may seem like a novel feature, but it is actually a very useful feature for static analyzers.

Final class constant

final class constants can be declared to prevent them from being overridden in subclasses.

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

class Bar extends Foo
{
    public const X = "bar";
}

Explicit octal digit representation

You can use 0o and 0o to represent octal numbers. The notation 0 preceded by a prefix is still valid.

16 === 0o16; // true
016 === 0O16; // true

Fiber path

Fibers is a primitive for implementing lightweight collaborative concurrency. They are a way to create blocks of code that can be paused and resumed like generators, but can be done from anywhere in the stack.

Fibers itself does not provide concurrency and still requires an event loop. However, they allow sharing the same API through blocking and non blocking implementations.

Fibers allows you to get rid of the boilerplate code you previously saw in Promise::then() or generator based collaborations. Libraries typically build further abstractions around Fiber, so you don't need to interact directly with them.

$fiber = new Fiber(function (): void {
    $valueAfterResuming = Fiber::suspend('after suspending');

    // ... 
});

$valueAfterSuspending = $fiber->start();

$fiber->resume('after resuming');

Array unpacking support for string keyed arrays

PHP previously supported unpacking inside an array through an extension operator, but only if the array has an integer key. You can now unpack arrays using string keys.

$array1 = ["a" => 1];
$array2 = ["b" => 2];
$array = ["a" => 0, ...$array1, ...$array2];

var_dump($array); // ["a" => 1, "b" => 2]

New array_is_list function

Occasionally, you may have to deal with the problem of determining whether the keys of the array are in numerical order, starting with index 0. Like json_encode determines whether an array should be encoded as an array or as an object.

$list = ["a", "b", "c"];
array_is_list($list); // true

$notAList = [1 => "a", 2 => "b", 3 => "c"];
array_is_list($notAList); // false

$alsoNotAList = ["a" => "a", "b" => "b", "c" => "c"];
array_is_list($alsoNotAList); // false

performance optimization

PHP 8.1 also has some performance changes, including:

  • JIT backend of ARM64 (AArch64)

  • Inherit cache (avoid relinking classes in every request)

  • Fast class name resolution (avoid lowercase and hash lookup)

  • timelib and ext/date performance improvements

  • Improvement of SPL file system iterator

  • Serialization / deserialization optimization

  • Some internal function optimizations (get_declared_classes(), expand(), strtr(), strnatcmp(), decodex())

  • JIT improvement and repair



The article comes from WeChat official account: PHP self learning center.

Tags: PHP

Posted on Fri, 26 Nov 2021 14:41:51 -0500 by gid