Brent Roose
Posted on November 8, 2021
enum Status
{
case draft;
case published;
case archived;
public function color(): string
{
return match($this)
{
Status::draft => 'grey',
Status::published => 'green',
Status::archived => 'red',
};
}
}
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,
) {}
}
class PostStateMachine
{
public function __construct(
private string $state = new Draft(),
) {
}
}
$fiber = new Fiber(function (): void {
$valueAfterResuming = Fiber::suspend('after suspending');
// …
});
$valueAfterSuspending = $fiber->start();
$fiber->resume('after resuming');
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]
Array unpacking also supports string keys
function foo(int $a, int $b) { /* … */ }
$foo = foo(...);
$foo(a: 1, b: 2);
function generateSlug(HasTitle&HasId $post) {
return strtolower($post->getTitle()) . $post->getId();
}
$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
💖 💪 🙅 🚩
Brent Roose
Posted on November 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
mac Install multiple PHP versions and automatically switch versions for each directory
November 17, 2022