Home  >  Article  >  Backend Development  >  PHP 8.2 updated! A quick overview of new features in one article

PHP 8.2 updated! A quick overview of new features in one article

藏色散人
藏色散人forward
2022-12-09 17:02:166840browse

PHP 8.2 Update Overview

Created time: December 8, 2022 10:50 PM

Last edited time: December 8, 2022 11:58 PM

Reprinted fromPHP 8.2 Highlights: What's New and Changed

? PHP 8.2 brings type system improvements, read-onlyreadonly classes, and sensitive parameter hiding Support, new randomrandom extensions, and features including simplifying and modernizing PHP.

PHP 8.2 is an important milestone in the modernization of PHP. In addition to exciting new features and improvements, PHP 8.2 works by deprecating dynamic property support, issuing warnings on INI configuration values, and fixing a number of legacy behaviors for array sorting and string conversions. [Recommended: PHP Video Tutorial]

Type System Improvement

PHP 8.2 solves several shortcomings and limitations of the original type system, allowing PHP projects to have better type safety. This includes adding support for the true type and allowing null and false to be used as independent types, as well as adding support for DNF types.

Disjoint Normal Form (DNF) type support - In PHP 8.2, developers can combine the union union type (PHP 8.0) with the intersectionintersection Types (PHP 8.1), which in turn allows for the declaration of more precise parameter, return and property types.

function process((HTMLRequest & RequestInterface) | APIRequest $request) {
 // ...}

(HTMLRequest & RequestInterface) | APIRequest The type declaration indicates that $request must be an instance of APIRequest, or implementHTMLRequest and RequestInterface.

On the other hand, after adding the true and false independent types, the bool type of the fixed return value can be changed to a specific one type.

function alwaysReturnsFalse(): false {}

function alwaysReturnsNull(): null {}

function alwaysReturnsTrue(): true {}

In the past, we have been able to define nullable parameters in the form of string|null, but in PHP 8.2, we will be able to use null## directly # As an independent type.

Read-only

readonly Class

PHP 8.1 adds support for read-only properties. Read-only types can only be assigned once during initialization, and subsequent modifications will be Prevent.

And PHP 8.2 extends the read-only attribute to the read-only class. When a class is declared read-only, all its properties are automatically declared read-only. Additionally, it ensures that all properties in read-only classes have type declarations.

// PHP 8.2
readonly class User {
    public string $username;
    public int $uid;
}

// PHP 8.1 等效写法
class User {
    public readonly string $username;
    public readonly int $uid;
}

New random

random Extension

Throughout the history of PHP, it has supported various random number generators (RNG). Each generator has different performance, usage scenarios, and security. PHP 8.2 restructures all RNG-related functions into a new extension named

random.

random The extension remains compatible with the existing API while providing the same functionality, so rand mt_rand random_bytes random_int and other functions can continue to work without any changes. But the random extension provides a new object-oriented API to generate random numbers with a modular architecture, making it easier to simulate RNGs and provide new RNGs, making testing projects safer and more convenient.

Constants in Trait

PHP 8.2 allows constants to be defined in Trait. Of course, you can't access Traits directly, but constants in Traits become class constants when inherited.

trait FooBar {
    const FOO = 'foo';
    private const BAR = 'bar';
    final const BAZ = 'baz';
    final protected const QUX = 'qux';
}

class Test {
    use FooBar;
}

echo Test::BAZ; // 'bar'

It should be noted that constants in Traits cannot conflict with constants in other Traits or classes.

Support hiding sensitive parameters

PHP 8.2 adds the

#[\SensitiveParameter] parameter annotation, which is used to hide the actual value in errors and stack information.

Functions that accept passwords, private keys, or other sensitive information can use

#[\SensitiveParameter] to hide the specific value. If an error or exception occurs, the corresponding value will be replaced with a \SensitiveParameterValue object.

PHP's built-in functions such as

password_hash and password_verify are annotated with #[\SensitiveParameter] parameters.

- function passwordHash(string $password)  {

+ function passwordHash(#[\SensitiveParameter] string $password)  {
        debug_print_backtrace();
    }
    passwordHash('hunter2');
array(1) {
    [0]=> array(4) {
        ["file"]=> string(38) "..."
        ["line"]=> int(9)
        ["function"]=> string(3) "foo"
        ["args"]=> array(1) {
-           [0]=> string(38) "hunter2"
+           [0]=> object(SensitiveParameterValue)#1 (0) {}
        }
    }
}

New functions and classes

Parse INI capacity

ini_parse_quantity
ini_parse_quantity('256M'); // 268435456

Keep CURL connection

curl_upkeep

The

curl_upkeep function in the PHP 8.2 Curl extension triggers the underlying Curl library to run the necessary tasks to keep the Curl connection active. The most common use case for this function is to keep an HTTP persistent connection (Keep-Alive) by calling the curl_upkeep function periodically.

Get encryption key length

openssl_cipher_key_length

In PHP 8.2 OpenSSL, there is a new function called

openssl_cipher_key_length which returns any supported The required key length (in bytes) of the OpenSSL cipher.

This feature eliminates the need to hardcode the key length required for OpenSSL cryptographic operations.

openssl_cipher_key_length("CHACHA20-POLY1305"); // 32

openssl_cipher_key_length("AES-128-GCM"); // 16

openssl_cipher_key_length("AES-256-GCM"); // 32

重置记录的内存使用峰值 memory_reset_peak_usage

PHP 8.2 添加了一个名为 memory_reset_peak_usage 的新函数,用于重置由 memory_get_peak_usage 函数返回的峰值内存使用量。

这对于多次调用或迭代一个动作并且需要记录每次调用的峰值内存使用量的应用程序很有帮助。 如果没有 memory_reset_peak_usage 函数重置内存使用情况,memory_get_peak_usage 将会返回整个运行过程中的绝对峰值内存使用情况。

PHP 8.2 弃用情况

PHP 8.2 也带来了相当一部分弃用。当语法、函数或特性被弃用时,PHP 会发出弃用通知,该通知不会中断 PHP 应用,但会记录到错误日志中。

弃用动态属性

PHP 8.2 中最值得注意的弃用之一是它弃用了动态声明的类属性。虽然可以忽略错误,但建议在类中声明类属性,加上类型声明就更好了。

class User {
    public int $uid;
}

$user = new User();
$user->name = 'Foo';
Deprecated: Creation of dynamic property User::$name is deprecated in ... on

许多古老的 PHP 应用程序很可能会受到此更改的影响,因为它们在扩展时往往不声明类属性,或者随着变化多年来不断发展。

当然了,选择忽略或例外也是存在的:

  • 匿名类及其子类(stdClass

  • 具有 __get__set 魔术方法的类

  • 具有 #[AllowDynamicProperties] 注解的类

弃用 utf8_encodeutf8_decode 函数

PHP 8.2 终于弃用这两名字跟实际效果不一致的函数,虽然名为 utf8 但实际上是 Latin 1 (ISO-8859-1)。

大多数使用这些函数的 PHP 项目往往没有意识到这个问题。推荐的替代品包括 mbstringiconvintl 扩展以提供更好的功能。

弃用 ${var} 字符串格式

PHP 一直支持使用 foo {$bar} 模式的字符串变量插值,以及将美元符号放在大括号外的替代语法 foo ${bar}

在 PHP 8.2 中,将美元符号放在花括号外的替代语法已弃用。

已弃用 推荐替代
Hello ${name} Hello {$name}
Hello ${$var} Hello {$$var}

此外,PHP 8.2 还弃用了一些部分支持的 callable 模式和 Mbstring 扩展对 Base64、Uuencode、QPrint 和 HTML 实体编码的处理。

The above is the detailed content of PHP 8.2 updated! A quick overview of new features in one article. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete