PHP 8.1 Modernization: Enums, Readonly Properties, and Beyond
The Era of Native Enumerations
PHP 8.1 finally brings
enum Status: string {
case Pending = 'pending';
case Shipped = 'shipped';
case Delivered = 'delivered';
}
You can now type-hint these specific cases in your methods. from() method to instantiate an 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
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 vapor.yml. Modernizing your stack hasn't been this straightforward in years.
