PHP 8.1 in 8 code blocks
source link: https://stitcher.io/blog/php-81-in-8-code-blocks
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Scout APM helps PHP developers pinpoint N+1 queries, memory leaks & more so you can troubleshoot fast & get back to coding faster. Start your free 14-day trial today.
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',
};
}
}
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
The new array_is_list
function
Noticed a tpyo? You can submit a PR to fix it.
If you want to stay up to date about what's happening on this blog, you can follow me on Twitter or subscribe to my newsletter:
Footnotes
New in PHP 8.1 — A comprehensive list of all things new in PHP 8.1
Readonly properties in PHP 8.1
New in initializers in PHP 8.1
Next up: Generics in PHP (video)Follow me: Twitter — RSS — Newsletter — Patreon — GitHub
© 2021 stitcher.io — Cookies & Privacy
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK