DEV Community

Brent Roose
Brent Roose

Posted on • Originally published at stitcher.io on

4 1

PHP 8.1 in 8 code blocks

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

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

Enums


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,
    ) {}
}
Enter fullscreen mode Exit fullscreen mode

Readonly properties


class PostStateMachine
{
    public function __construct(
        private string $state = new Draft(),
    ) {
    }
}
Enter fullscreen mode Exit fullscreen mode

New in initializers


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

    // … 
});

$valueAfterSuspending = $fiber->start();

$fiber->resume('after resuming');
Enter fullscreen mode Exit fullscreen mode

Fibers, a.k.a. "green threads"

Do you want to learn more about PHP 8.1? There's The Road to PHP 8.1. For the next 10 days, you'll receive a daily email covering a new and exiting feature of PHP 8.1; afterwards you'll be automatically unsubscribed, so no spam or followup. Subscribe now!

$array1 = ["a" => 1];

$array2 = ["b" => 2];

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

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

Array unpacking also supports string keys


function foo(int $a, int $b) { /* … */ }

$foo = foo(...);

$foo(a: 1, b: 2);
Enter fullscreen mode Exit fullscreen mode

First class callables


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

Pure intersection types


$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
Enter fullscreen mode Exit fullscreen mode

The new array_is_list function

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay