亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Union Types (PHP 8.1)
Readonly Properties and Classes (PHP 8.1 & 8.2)
Enums (PHP 8.1)
First-Class Callable Syntax (PHP 8.1)
Fiber Support (PHP 8.1)
Never Return Type (PHP 8.1)
New str_contains() Function (PHP 8.0)
Match Expressions (PHP 8.0)
Constructor Property Promotion (PHP 8.0)
Performance Improvements
Home Backend Development PHP Tutorial What are the new features in PHP 8 (8.0, 8.1, 8.2, 8.3)?

What are the new features in PHP 8 (8.0, 8.1, 8.2, 8.3)?

Jun 28, 2025 am 02:13 AM

PHP versions 8.0 to 8.3 introduce a number of new features to improve language capabilities. 1. PHP 8.1 supports Union Types, allowing function parameters or return values ??to declare multiple types, such as int|float; 2. Introduce read-only attributes and classes to ensure immutability after initialization; 3. Add enumeration types to reduce the use of magic strings; 4. Support first-class citizen callable syntax to simplify functional programming; 5. Introduce Fiber to implement collaborative multitasking; 6. Add never return type, making it clear that the function does not return; 7. PHP 8.0 has added str_contains() function to improve string judgment readability; 8. Introduce match expressions to replace switch statements to make it more concise and safe; 9. Constructor attributes improve and reduce boilerplate code; 10. Each version continuously optimizes performance to improve execution speed and memory efficiency.

What are the new features in PHP 8 (8.0, 8.1, 8.2, 8.3)?

PHP has been evolving steady, and since the release of PHP 8.0 in late 2020, each minor version (8.1, 8.2, and now 8.3) has brought useful features, performance improvements, and better developer ergonomics. If you're maintaining or building modern PHP applications, it's worth knowing what's new across these versions — especially if you're considering upgrading.

Union Types (PHP 8.1)

One of the more impactful additions in PHP 8.1 is union types . Before this, if a function could accept multiple types, you had to rely on docblocks or just use mixed . Now, you can explicitly declare that a parameter or return value supports multiple types directly in the function signature.

Example:

 function setLength(int|float $length): void {
    // ...
}

This helps with code clarity and allow static analyzers and IDEs to catch issues earlier. It also plays well with type-safe frameworks and tools.

Note: There's also a | syntax for separating types, and null can be included like string|null .

Readonly Properties and Classes (PHP 8.1 & 8.2)

PHP 8.1 introduced readonly properties , which prevent property mutation after initialization. This is great for immutable data structures:

 class User {
    public function __construct(
        public readonly string $name,
        public readonly int $id
    ) {}
}

In PHP 8.2, this was extended to readonly classes , where all properties are implicitly readonly:

 readonly class User {
    public function __construct(
        public string $name,
        public int $id
    ) {}
}

These features help enforce immutability without boilerplate code, making models safer and easier to reason about.

Enums (PHP 8.1)

Enums are one of those features that make your code cleaner when dealing with fixed sets of values. PHP 8.1 added backed and pure enums .

Example of a backed enum:

 enum Status: string {
    case DRAFT = 'draft';
    case PUBLISHED = 'published';
}

You can access the value via Status::DRAFT->value , and even match against cases. Pure enums don't have backing values ??and are used more as symbolic constants.

Enums reduce magic strings in your codebase and allow for better validation and autocomplete in IDEs.

First-Class Callable Syntax (PHP 8.1)

This feature simplifies how you pass functions as calls. Instead of writing:

 array_map(fn($x) => strlen($x), $arr);

Now you can write:

 array_map(strlen(...), $arr);

Behind the scenes, it converts strlen(...) into a closure. This makes functional-style programming cleaner and less verbose, especially when chaining operations.

Fiber Support (PHP 8.1)

Fibers enable cooperative multitasking , which opens the door for async programming patterns in PHP. While PHP traditionally follows a synchronous request-response model, Fibers provides a foundation for future event-driven frameworks.

They're not widely used yet in most applications, but they're an important under-the-hood improvement that may shape how long-running PHP scripts behave in the future.

Never Return Type (PHP 8.1)

The never return type indicates that a function does not return — either because it throws an exception or terminates execution.

Example:

 function redirect(string $url): never {
    header("Location: $url");
    exit();
}

This helps static analysis tools understand your intent better and avoid false positives in code inspection.

New str_contains() Function (PHP 8.0)

Before PHP 8.0, checking if a string contains another string required using strpos() and comparing to false . Now, there's a clean built-in helper:

 if (str_contains('Hello World', 'World')) {
    // true
}

It's small but improves readability and reduces bugs from incorrect comparisons.

Match Expressions (PHP 8.0)

Match expressions are like enhanced switch statements. They return a value and do strict comparisons automatically.

Example:

 $status = match($code) {
    200 => 'OK',
    404 => 'Not Found',
    default => 'Unknown'
};

It's shorter than a traditional switch and avoids common pitfalls like missing break statements.

Constructor Property Promotion (PHP 8.0)

This cuts down on boilerplate in classes by allowing you to define and assign properties directly in the constructor:

 class Point {
    public function __construct(
        public float $x,
        public float $y,
        private float $z
    ) {}
}

No need to separately declare properties and assign them — it's done in one step.

Performance Improvements

Each new PHP 8 version includes optimizations that improve speed and reduce memory usage. For example, PHP 8.1 saw improvements in array handling and internal function calls, while PHP 8.2 optimized JIT compilation further. You might see up to 10–20% performance gains over older PHP 7.x versions depending on your workload.

If you're running older PHP versions, simply upgrading to 8.x can give a noticeable performance boost — especially for high-traffic apps.


That's a broad overview of what's new in PHP 8.0 through 8.3. These changes aren't flashy, but they make writing and maintaining PHP code smoother and safer. Whether it's better typing, cleaner syntax, or improved runtime behavior, the updates add up to a more modern and capable language.

The above is the detailed content of What are the new features in PHP 8 (8.0, 8.1, 8.2, 8.3)?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
PHP Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

See all articles