The Era of Native Enumerations PHP 8.1 finally brings Enums into the core, eliminating the need for brittle class constants or manual validation logic. An Enum 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. ```php enum Status: string { case Pending = 'pending'; case Shipped = 'shipped'; case Delivered = 'delivered'; } ``` You can now type-hint these specific cases in your methods. Laravel developers benefit further as Eloquent supports Enum casting, automatically converting database strings into rich objects. Use the `from()` method to instantiate an Enum 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 Data Transfer Objects (DTOs) where you want to guarantee immutability after creation. ```php 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: ```php 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 Laravel Forge or Laravel Vapor, upgrading is seamless. Forge allows one-click PHP version switching in the Meta section, while Vapor users simply update the runtime in `vapor.yml`. Modernizing your stack hasn't been this straightforward in years.
PHP 8.1
Software
Oct 2021 • 1 videos
High activity month for PHP 8.1. Laravel among the most active voices, with 1 videos across 1 sources.
Oct 2021
- Oct 25, 2021