PHP 8.1 Modernization: Enums, Readonly Properties, and Beyond

The Era of Native Enumerations

PHP 8.1 finally brings

into the core, eliminating the need for brittle class constants or manual validation logic. An
PHP 8.1
defines a fixed set of possible values, such as an order status or a user role. This provides immediate type safety at the engine level.

enum Status: string {
    case Pending = 'pending';
    case Shipped = 'shipped';
    case Delivered = 'delivered';
}

You can now type-hint these specific cases in your methods.

developers benefit further as
Eloquent
supports
PHP 8.1
casting, automatically converting database strings into rich objects. Use the from() method to instantiate an
PHP 8.1
from a raw value, or tryFrom() if you need a nullable return for invalid inputs.

Immutable State with Readonly Properties

Managing data integrity becomes significantly easier with the readonly modifier. Once a property is initialized—usually within a constructor—it cannot be modified. This is a massive win for

where you want to guarantee immutability after creation.

public readonly string $email;

Note that readonly requires a typed property. It prevents accidental side effects elsewhere in your application, ensuring that once your object is in a valid state, it stays that way.

Streamlining Initializers and Types

PHP 8.1 introduces "new" in initializers, allowing you to use objects as default parameter values. Previously, you had to default to null and instantiate the object inside the method body. Now, the syntax is clean and expressive:

public function __construct(
    public Order $order = new Order(),
) {}

Additionally, Intersection Types allow you to require a value to satisfy multiple interfaces simultaneously using the & operator. This is perfect for complex services where an object must be both Authenticable and Authorizable, providing granular control over your dependency injection.

Practical Deployment in Laravel

If you use

or
Laravel Vapor
, upgrading is seamless.
Laravel Forge
allows one-click PHP version switching in the Meta section, while
Laravel Vapor
users simply update the runtime in vapor.yml. Modernizing your stack hasn't been this straightforward in years.

2 min read