Enums introduced in PHP 8.1 provides a type-safe constant collection, solving the magic value problem; 1. Use enum to define fixed constants, such as Status::Draft, to ensure that only predefined values are available; 2. Bind enums to strings or integers through Backed Enums, and support from() and tryFrom() to convert between scalars and enums; 3. Enumerations can define methods and behaviors, such as color() and isEditable(), to enhance business logic encapsulation; 4. Applicable to static scenarios such as state and configuration, not for dynamic data; 5. It can implement the UnitEnum or BackedEnum interface for type constraints, improve code robustness and IDE support, which is an important feature of modern PHP development.
PHP 8.1 introduced Enums (enums) , which marked an important step forward in PHP in terms of type safety and code maintainability. In the past, we often used class constants or global constants to simulate encoded performance, but these methods lack type constraints, cannot prevent illegal values from being passed in, and it is difficult to get good prompts in the IDE. The emergence of Enums is precisely to solve these problems.

What is Enum?
Enumeration is a special data type used to define a set of named constants. In PHP 8.1, enum
becomes a keyword natively supported by the language, allowing you to define a type whose value can only be one of a few predefined options.
enum Status { case Draft; case Published; case Archived; }
Now, Status::Draft
, Status::Published
and Status::Archived
are the only legal values. You can no longer pass strings or numbers like 'draft'
or 1
at will - this greatly enhances type safety.

Improve type safety: From "magic value" to explicit types
Before there are enumerations, we often see code like this:
function setStatus(string $status): void { if (!in_array($status, ['draft', 'published', 'archived'])) { throw new InvalidArgumentException('Invalid status'); } // ... }
The problem with this writing is:

-
'draft'
is a "magic string" that is easy to spell. - There is no compile-time check, and errors can only be found at runtime.
- The IDE cannot infer the legal value.
After using Enum:
function setStatus(Status $status): void { // The type system ensures that the passed in a legal Status enum value} // setStatus(Status::Draft);
Now, if you pass in an illegal value, PHP will directly report an error (especially when strict type is enabled), and the IDE can also provide automatic completion and error prompts.
Backed Enums: Bind scalar values
Sometimes we want the enum value to correspond to a specific string or integer (such as stored in a database). PHP 8.1 provides Backed Enums to support this.
enum OrderStatus: string { case Pending = 'pending'; case Shipped = 'shipped'; case Delivered = 'delivered'; }
You can easily convert between enum and scalar:
// Create an enum from a string $status = OrderStatus::from('pending'); // Return OrderStatus::Pending $status = OrderStatus::tryFrom('unknown'); // Return null (no exception thrown) // Get the underlying value echo $status->value; // Output 'pending'
This is very practical in handling database, API requests and other scenarios - you can safely convert strings into enums, and then use type prompts to ensure the subsequent logic is correct.
Enumeration methods and behavior extensions
Enumerations can not only contain constants, but also define methods and even implement interfaces.
enum Status { case Draft; case Published; case Archived; public function color(): string { return match($this) { self::Draft => 'gray', self::Published => 'green', self::Archived => 'red', }; } public function isEditable(): bool { return $this === self::Draft || $this === self::Published; } }
Example of usage:
echo Status::Draft->color(); // gray var_dump(Status::Archived->isEditable()); // false
This makes enums more than just "sets of values" but can carry behavior and become part of the real domain model.
Actual suggestions and usage scenarios
- ?Status fields : Order status, article status, user role, etc.
- ?Configuration options : For example
OutputFormat::Json
,OutputFormat::Xml
. - ?Form input verification : Use in combination with DTO to ensure that the input values belong to a legal set.
- ? Don't abuse: If the value is dynamic (such as from the database configuration table), it is not suitable for enumeration.
Tips: You can let Enum implement
UnitEnum
orBackedEnum
interface to do type constraints, for example:function processEnum(UnitEnum $enum): void { ... }
Summarize
PHP 8.1's Enums is not just a syntax sugar, it brings true type safety, better readability and stronger tool support. By eliminating the “magic value” and improving the robustness of the code, it is changing the way we organize constants and states.
Basically all this is it - it's not complicated, but once it's used, it can't be returned.
The above is the detailed content of PHP 8.1 Enums: A New Paradigm for Type-Safe Constants. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

UpgradePHP7.xcodebasestoPHP8 byreplacingPHPDoc-suggestedtypeslike@paramstring|intwithnativeuniontypessuchasstring|intforparametersandreturntypes,whichimprovestypesafetyandclarity;2.Applyuniontypestomixedinputparameters(e.g.,int|stringforIDs),nullable

PHP supports the coexistence of loose types and strict types, which is the core feature of its evolution from scripting languages to modern programming languages. 1. Loose types are suitable for rapid prototyping, handling dynamic user input, or docking with external APIs, but there are problems such as risk of implicit type conversion, difficulty in debugging and weak tool support. 2. Strict type is enabled by declare(strict_types=1), which can detect errors in advance, improve code readability and IDE support, and is suitable for scenarios with high requirements for core business logic, team collaboration and data integrity. 3. Mixed use should be used in actual development: Strict types are enabled by default, loose types are used only when necessary at the input boundaries, and verification and type conversion are performed as soon as possible. 4. Recommended practices include using PHPSta

AcallableinPHPisapseudo-typerepresentinganyvaluethatcanbeinvokedusingthe()operator,usedprimarilyforflexiblecodeincallbacksandhigher-orderfunctions;themainformsofcallablesare:1)namedfunctionslike'strlen',2)anonymousfunctions(closures),3)objectmethodsv

Enums introduced in PHP8.1 provides a type-safe constant collection, solving the magic value problem; 1. Use enum to define fixed constants, such as Status::Draft, to ensure that only predefined values are available; 2. Bind enums to strings or integers through BackedEnums, and support conversion from() and tryFrom() between scalars and enums; 3. Enums can define methods and behaviors, such as color() and isEditable(), to enhance business logic encapsulation; 4. Applicable to static scenarios such as state and configuration, not for dynamic data; 5. It can implement the UnitEnum or BackedEnum interface for type constraints, improve code robustness and IDE support, and is

0.1 0.2!==0.3inPHPduetobinaryfloating-pointprecisionlimitations,sodevelopersmustavoiddirectcomparisonsanduseepsilon-basedchecks,employBCMathorGMPforexactarithmetic,storecurrencyinintegerswhenpossible,formatoutputcarefully,andneverrelyonfloatprecision

PHP uses zval structure to manage variables. The answer is: 1. zval contains values, types and metadata, with a size of 16 bytes; 2. When the type changes, only the union and type information need to be updated; 3. Complex types refer to structures with reference counts through pointers; 4. When assigning values, copy is used to optimize memory; 5. References make variables share the same zval; 6. Recycling references are processed by a special garbage collector. This explains the underlying mechanism of PHP variable behavior.

The life cycle of PHP resources is divided into three stages: 1. Resource creation, obtaining external system handles through functions such as fopen and curl_init; 2. Resource usage, passing resources to related functions for operation, PHP maps to the underlying system structure through resource ID; 3. Resource destruction, manually calling fclose, curl_close and other functions should be given priority to release resources to avoid relying on automatic garbage collection to prevent file descriptors from exhausting. Best practices include: always explicitly close resources, use try... finally ensure cleanup, prioritize objects such as PDO that supports __destruct, avoid global storage resources, and monitor active resources through get_resources()

==performsloosecomparisonwithtypejuggling,===checksbothvalueandtypestrictly;1."php"==0istruebecausenon-numericstringsconvertto0,2.emptystrings,null,false,and0arelooselyequal,3.scientificnotationlike"0e123"=="0e456"cancau
