![]() Public static function tryFrom(int|string $value): ?static * Same as from(), but returns a null if no matching case is found. Public static function from(int|string $value): static * Returns the enum case matching the given value, if found. * Returns an array with all cases for the enum implementation. Visibility is only useful for hiding internal aspects of how the enum performs work, since inheritance is not possible.Įnums themselves implement one of the following internal interfaces: // For standard enums: Enums cannot be extended, and cannot inherit from other classes.As an example, in our HTTP\ResponseStatus enumeration above, if defined a reasonPhrase() method that returned a string (e.g., public function reasonPhrase(): string), you would invoke it using a specific case: echo ResponseStatus::400->reasonPhrase(). Instead, instance methods apply to individual enumeration cases. This means no properties, and it also means you cannot use new to create an instance. Note that all values must be of the same type, and each value MUST be unique the backed type is on the enum declaration itself.Įnums can define methods, and also implement interfaces, which means they can have behavior. A classic example is declaring HTTP request methods or response status codes: namespace HTTP A backed enum holds a value for each case, where the value may be either a string or an integer. Passing anything else would raise an error. When calling the above function, you would pass a specific enumerated value: travel(Vehicle::Ferry) As a basic example, we might define a Vehicle enum with allowed styles of transportation: enum VehicleĬode that consumes or returns enums would provide a typehint using the enum: function travel(Vehicle $vehicle): void Enums are available in a wide number of programming languages, and have been an often-requested feature for PHP for many years now. EnumsĮnumerations, also known as enumerated types or enums, are types that have a fixed number of possible values. What follows is a breakdown of some of the larger features that arrived with 8.1. PHP 8.1 offers more than two dozen new features, from smaller additions like adding a new $options argument to the various hash_*() functions, to entirely new syntax features such as Enumerations. The main reason for a new minor release is to provide new features. Passing null to non-nullable parameters.Return types in interfaces and internal classes.Array unpacking for arrays with string keys.Let's see what's in store for you early adopters! ![]() Released on November 25, 2021, PHP 8.1 is the first minor release in the PHP 8 series, and comes with its own new features and deprecations. Each year brings a new major or minor release of PHP, and this year is no different. ![]()
0 Comments
Leave a Reply. |