Home  >  Article  >  Backend Development  >  PHP 8.3 big release: innovation and enhancement, creating the future

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

DDD
DDDOriginal
2023-11-24 11:01:111930browse

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();
    }
}

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';
}

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;// 故意重写
    }
}

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

数组中的负索引

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 中

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

匿名只读类

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

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

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

新函数 json_validate

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

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

该函数简化了 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);

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

动态类常量获取

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

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

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

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

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:
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