Table of Contents
Enhancements of read-only classes
Typed Class Constants
#[Override] 属性
数组中的负索引
匿名只读类
新函数 json_validate
Randomizer 增强
动态类常量获取
更具针对性的日期/时间异常
优化了 unserialize() 错误处理
range() function improvements
Traits and Static Properties
Stack Overflow Detection
New function mb_str_pad
Magic Method Closures and Named Parameters
Invariant constant visibility
Deprecations
Home Backend Development PHP8 PHP 8.3 big release: innovation and enhancement, creating the future

PHP 8.3 big release: innovation and enhancement, creating the future

Nov 24, 2023 am 11:01 AM
php

PHP 8.3 was released on November 23, 2023, marking another important step in the evolution of the language. This release introduces many new features, performance improvements, and deprecations designed to enhance the PHP development experience. In this comprehensive guide, we'll take a deep dive into these updates, providing insights, tips, and creative code examples to help you adapt and get the most out of PHP 8.3.

Enhancements of read-only classes

PHP 8.3 has modified the cloning behavior of read-only classes to allow re-initialization of read-only properties during cloning. This change addresses a specific edge case in deep cloning. Refer to the following example:

class Article {
    public readonly DateTime $publishedOn;
    public function __construct(DateTime $publishedOn) {
        $this->publishedOn = $publishedOn;
    }
    public function __clone() {
        // PHP 8.3 允许
        $this->publishedOn = new DateTime();
    }
}
Copy after login

This change allows more flexibility in managing read-only properties, especially when copying objects with complex structures .

Typed Class Constants

PHP 8.3 allows developers to specify types for class constants, improving type safety and making code cleaner. For example:

class Config {
    const API_KEY = 'your-api-key';
}
Copy after login

This feature enhances the robustness of class constants, making them an integral part of the class contract.

#[Override] 属性

PHP 8.3 中的 #[Override]属性用于声明某个方法有意重写父方法。该属性可在重命名或删除父方法时捕获错误,从而提高代码质量。例如:

abstract class BaseClass
{
    public function defaultMethod(): int
    {
        return 1;
    }
}
final class DerivedClass extends BaseClass
{
    #[Override]
    public function defaultMethod(): int
    {
        return 2;// 故意重写
    }
}
Copy after login

属性增加了额外的安全层,确保您的覆盖始终是有意且可识别的。

数组中的负索引

PHP 8.3 对数组处理负索引方式进行了改进。在以前的版本中,如果使用负索引将一个项目添加到空数组,然后添加另一个项目,则第二个项目会从 0 开始。在 PHP 8.3 中,第二个项目将放置在下一个负索引处,即 -1。例如:

$array = [];
$array[-1] = '第一个';
$array[] = '第二';
var_export($array); // [&#39;first&#39;, &#39;second&#39;] 在 PHP < 8.3 中,[&#39;first&#39;, &#39;second&#39;] 在 PHP 8.3 中
Copy after login

一变化使得负指数的处理更加可预测和一致。

匿名只读类

PHP 8.3 引入了对匿名类标记为只读的支持,这为动态创建不可变对象提供了更大的灵活性。例如:

$anonymousClass = new readonly class {
    public function __construct(
        public string $name = &#39;Anonymous&#39;,
    ) {}
};
Copy after login

增强功能使只读类在各种编程场景中更加通用,扩大了其应用范围。

新函数 json_validate

PHP 8.3 新增的 json_validate() 函数提供了一种节省内存的方法来检查字符串是否为有效的 JSON。此函数特别适用于需要验证 JSON 而不对其进行解码的场景。它的工作原理如下:

$jsonString = &#39;{"姓名": "小明", "年龄": 20}&#39;;
$isJsonValid = json_validate($jsonString);
Copy after login

该函数简化了 JSON 验证,使其更加高效和简单。

Randomizer 增强

PHP 8.3 对 PHP 8.2 中引入的 Randomizer 类进行了增强,新增了从字符串生成随机字节以及获取指定范围内的随机浮点数的方法。例如:

$randomizer = new Randomizer();
$randomBytes = $randomizer->getBytesFromString(&#39;abcdef&#39;, 4);
$randomFloat = $randomizer->getFloat(0.0, 1.0);
Copy after login

新方法扩展了 Randomizer 类的功能,使其能够生成更丰富、更灵活的随机数据。

动态类常量获取

PHP 8.3 新增了动态获取类常量的语法,使代码在使用常量时更加灵活、易读。例如:

class Setting {
  const MODE = &#39;产生&#39;;
  public static function getCurrentMode() {
    return static::MODE;
  }
}
$currentMode = Setting::getCurrentMode();
Copy after login

这种语法简化了动态访问类常量的过程,增强了代码的可读性和可维护性。

更具针对性的日期/时间异常

PHP 8.3 对日期和时间函数的异常处理进行了改进,新增了针对特定错误情况的专用异常。此改进使错误报告更加描述性和准确,从而提高了调试和处理日期/时间相关问题的效率。

优化了 unserialize() 错误处理

PHP 8.3 中的 unserialize() 函数在遇到问题时始终抛出 E_WARNING 错误,从而提供更统一和可预测的错误处理。此更改简化了序列化场景中的调试和错误处理。

range() function improvements

PHP 8.3 has made many improvements to the range() function, including throwing a TypeError exception for invalid boundary input, And throw ValueError exception for invalid step value. These improvements make the function's behavior more intuitive and consistent.

Traits and Static Properties

In PHP 8.3, using a trait with static properties will redeclare the static properties inherited from the parent class, creating a separate static property store for the current class. This change makes the behavior of static properties in traits consistent with the behavior of static properties in classes.

Stack Overflow Detection

PHP 8.3 adds a new INI directive to detect stack overflow to prevent segmentation faults. This feature enhances the stability and reliability of PHP applications, especially in complex or recursive scenarios.

New function mb_str_pad

PHP 8.3’s new mb_str_pad() function fills the gap of multi-byte string functions, for processing multi-bytes such as UTF-8 Encoding is crucial. This function ensures that the string is correctly populated regardless of encoding.

Magic Method Closures and Named Parameters

PHP 8.3 enhances the flexibility and expressiveness of magic methods by allowing you to create closures from magic methods and pass named parameters to these closures, making them more Powerful and versatile.

Invariant constant visibility

PHP 8.3 fixes the bug of constant visibility checking when implementing interfaces. This change ensures consistent visibility of constants, consistent with the general principles of visibility in PHP.

Deprecations

As always, PHP 8.3 includes a number of deprecations to phase out outdated or less efficient features and move the language forward. These deprecations include changes to functions such as mb_strimwidth() and ldap_connect().

The release of PHP 8.3 is another milestone in the continuous development and improvement of the PHP language. New features, enhancements, and deprecations provide developers with more tools and capabilities for writing more efficient, robust, and maintainable code. As you explore and adopt these changes, be sure to test your applications thoroughly and stay informed of the latest developments in the PHP ecosystem.

The above is the detailed content of PHP 8.3 big release: innovation and enhancement, creating the future. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles