If you enjoy reading my blog, you could consider supporting me on Patreon.

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
    public function onProductCreated(ProductCreated $event) { /* … */ }

    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.


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.

public function(
    string $parameterA,
    int $parameterB,
    Foo $objectfoo,
) {
    // …

Trailing commas are allowed in parameter lists

str_contains('string with lots of words', 'words');

str_starts_with('haystack', 'hay');

str_ends_with('haystack', 'stack');

New string functions.

Let's not fool ourselves: 8 code blocks isn't enough to summarise all great new things in PHP 8. So let's just add a few more.

function bar(Stringable $stringable) { /* … */ }

A new Stringable interface.


Call ::class directly on objects.

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.

Would you like to stay up to date about new content? Feel free to subscribe to my newsletter and follow me on Twitter. Noticed a tpyo? You can submit a PR to fix it.