PHP 8 in 8 code blocks - stitcher.io
source link: https://www.stitcher.io/blog/php-8-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.
« back — written by Brent on May 15, 2020
PHP 8 in 8 code blocks
PHP 8 brings lots of new features, in this list we'll look at the most outstanding ones. If you want a full list and background information, you can read about all things new in PHP 8.
use Support\Attributes\ListensTo;
class ProductSubscriber
{
#[ListensTo(ProductCreated::class)]
public function onProductCreated(ProductCreated $event) { /* … */ }
#[ListensTo(ProductDeleted::class)]
public function onProductDeleted(ProductDeleted $event) { /* … */ }
}
Attributes — aka annotations — you can read about them in depth in this post.
public function foo(Foo|Bar $input): int|float;
public function bar(mixed $input): mixed;
Union types allows for type hinting several types. There's also a new mixed
type which represents several types at once.
interface Foo
{
public function bar(): static;
}
The static
return type is built-in.
[JIT]
opcache.jit=1225
The just-in-time compiler for PHP.
$triggerError = fn() => throw new MyError();
$foo = $bar['offset'] ?? throw new OffsetDoesNotExist('offset');
throw
can be used in expressions.
try {
// Something goes wrong
} catch (MySpecialException) {
Log::error("Something went wrong");
}
Non-capturing catches: no need to specify an exception variable if you don't need it.
setcookie(
name: 'test',
expires: time() + 60 * 60 * 2,
);
$result = match($input) {
0 => "hello",
'1', '2', '3' => "world",
};
The match
expression as an improvement to the switch
expression.
Interested in more?
I've written a book that teaches all about modern PHP development and PHP 8. Now with 30% off for black friday!
There's even more. If you want a full list, you can find it on this blog.
What feature are you looking forward to the most? Let me know on Twitter or via email.
Footnotes
New in PHP 8 — A comprehensive list of all things new in PHP 8
Attributes in PHP 8 — A close look at attributes, also known as annotations
The JIT in PHP 8 — A close look at the JIT, and what it means for PHP
Next up: What's new in PHP 8Follow me: Twitter — RSS — Newsletter — Patreon — GitHub
© 2020 stitcher.io — Cookies & Privacy
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK