Table of Contents
Type system improvements
readonly Class
random Extension
Parse INI capacityini_parse_quantity
ini_parse_quantity('256M'); // 268435456
Copy after login
" >Parse INI capacityini_parse_quantity
ini_parse_quantity('256M'); // 268435456
Copy after login
Keep CURL connectioncurl_upkeep
获取加密密钥长度 openssl_cipher_key_length
重置记录的内存使用峰值 memory_reset_peak_usage
PHP 8.2 弃用情况
弃用动态属性
弃用 utf8_encodeutf8_decode 函数
弃用 ${var} 字符串格式
Home Backend Development PHP8 A brief discussion on the update progress of PHP 8.2

A brief discussion on the update progress of PHP 8.2

Dec 15, 2022 am 11:43 AM
php

PHP 8.2 brings type system improvements, readonly `readonly` classes, sensitive parameter hiding support, a new random `random` extension, and many features including simplifying and modernizing PHP , let’s take a look at it, I hope it will be helpful to everyone.

A brief discussion on the update progress of PHP 8.2

Recommended learning: "PHP Video Tutorial"

PHP 8.2 brings type system improvements, read-onlyreadonly classes, sensitive parameter hiding support, new random random extensions, and many 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.

Type system improvements

PHP 8.2 resolves 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) {
 // ...
}
Copy after login

(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 {}
Copy after login

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;
}
Copy after login

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'
Copy after login

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');
Copy after login
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) {}
        }
    }
}
Copy after login

New functions and classes

Parse INI capacityini_parse_quantity
ini_parse_quantity('256M'); // 268435456
Copy after login

Keep CURL connectioncurl_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 is 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.

获取加密密钥长度 openssl_cipher_key_length

在 PHP 8.2 OpenSSL 中,有一个名为 openssl_cipher_key_length 的新函数,它返回任何受支持的 OpenSSL 密码所需的密钥长度(以字节为单位)。

此功能消除了对 OpenSSL 密码操作所需密钥长度进行硬编码的需要。

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

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

openssl_cipher_key_length("AES-256-GCM"); // 32
Copy after login

重置记录的内存使用峰值 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';
Copy after login
Deprecated: Creation of dynamic property User::$name is deprecated in ... on
Copy after login

许多古老的 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 实体编码的处理。

推荐学习:《PHP视频教程

The above is the detailed content of A brief discussion on the update progress of PHP 8.2. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
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.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles