Home Backend Development PHP Tutorial What changes will be included in PHP8.2 (performance improvements, new features)!

What changes will be included in PHP8.2 (performance improvements, new features)!

Jul 04, 2022 pm 02:28 PM
php

The release time of PHP8.2 has not yet been determined, but it is expected to be released at the end of 2022. This article will introduce you to the features, performance improvements, deprecated features, etc. in the new version.

Related recommendations: The latest progress of PHP8.2, new features will be frozen soon!

null and false will be treated as independent types

PHP will not fall into the direction of perfect type safety , but from a technical point of view, it is worthwhile to treat null and false as independent data types. Under normal circumstances, many common functions in PHP will indicate an error by returning false. For example, in file_get_content:

1

file_get_contents(/* … */): string|false

Copy after login

In the past, false could be used in union types, but it could not be used independently. In PHP8.2, it can be used alone: ​​

1

2

3

4

function alwaysFalse(): false

{

    return false;

}

Copy after login

Of course, for this approach, Some developers are wary. It does not support true as an independent type. These developers believe that false is just a value and that types should represent categories rather than values. Of course, in the type system, there is a concept of unit type, which is a type that only allows one value. But does this really work?

But another RFC is also discussing adding true as a type to PHP.

An independent null is very meaningful, so that the empty object pattern can be simply implemented:

1

2

3

4

5

6

7

8

9

class Post

{

    public function getAuthor(): ?string { /* … */ }

}

 

class NullPost extends Post

{

    public function getAuthor(): null { /* … */ }

}

Copy after login

This can be said for NullPost::getAuthor() that it will only return null, no need to do it like before In that case, null and string must be jointly declared together.

Deprecate dynamic properties

This is a better design for the language specification, but it also restricts many uses. Dynamic properties are deprecated in PHP 8.2 and will throw error exceptions in PHP.

What are dynamic properties? That is, you did not declare these properties in the class, but you can still set and get them:

1

2

3

4

5

6

7

8

class Post

{

    public string $title;

}

 

// …

 

$post->name = 'Name';  // 在PHP8.2中不能这样使用,因为并没有在类中声明

Copy after login

But don’t worry, magic methods such as __set and __get will still work as expected:

1

2

3

4

5

6

7

8

9

10

11

12

13

class Post

{

    private array $properties = [];

 

    public function __set(string $name, mixed $value): void

    {

        $this->properties[$name] = $value;

    }

}

 

// …

 

$post->name = 'Name';

Copy after login

Standard objects Same thing: stdClass will continue to support dynamic properties.

PHP used to be a highly dynamic dynamic language, but now many people are willing to accept more rigorous programming methods. Being as strict as possible and relying on static analysis as much as possible is a good thing, because it allows developers to write better code.

However, some developers who value dynamic properties may be very dissatisfied with this change. If you don’t want to see these warnings when using PHP8.2, you can do this:

Yes Using #[AllowDynamicProperties]

1

2

3

4

5

6

7

8

9

#[AllowDynamicProperties]

class Post

{

    public string $title;

}

 

// …

 

$post->name = 'Name'; // 一切正常

Copy after login

Another way is to modify the alarm level, but this is not recommended. You will run into trouble when you plan to upgrade to PHP9.0.

1

error_reporting(E_ALL ^ E_DEPRECATED);

Copy after login

Parameter desensitization when tracing calls

What is parameter desensitization? When we develop, when we encounter errors, we use Trace to debug, but the current stack records some sensitive data, such as environment variables, passwords, and users.

In PHP8.2, some editing of parameters is allowed (Redact, let’s call it editing, has some modification meaning, but it is not appropriate to call it modification directly), such as desensitizing some parameters, so that these The calling value of the parameter will not be listed in the stack information:

1

2

3

4

5

6

7

8

9

function test(

    $foo,

    #[\SensitiveParameter] $bar,

    $baz

) {

    throw new Exception('Error');

}

 

test('foo', 'bar', 'baz');

Copy after login

If an error is reported, you will find that the second parameter bar does not record the actual value. This can have a desensitizing effect. If the password is passed, it will not be recorded.

1

2

3

4

5

Fatal error: Uncaught Exception: Error in test.php:8

Stack trace:

#0 test.php(11): test('foo', Object(SensitiveParameterValue), 'baz')

#1 {main}

  thrown in test.php on line 8

Copy after login

The calling methods of some objects are deprecated

Some previous methods of calling objects are deprecated. Some of these need to be called through call_user_func($callable), rather than being called directly by $callable().

1

2

3

4

5

6

7

8

"self::method"

"parent::method"

"static::method"

["self", "method"]

["parent", "method"]

["static", "method"]

["Foo", "Bar::method"]

[new Foo, "Bar::method"]

Copy after login

Why do you do this? Nikita explained it well in the RFC discussion:

These deprecated calls are context-specific, and the method referred to by "self::method" depends on which class the call is executed from or Callability check. In fact, this usually applies to the last two cases as well when used in the form [new Foo, "parent::method"].

Reducing the context dependency of callable objects is a secondary goal of this RFC. After this RFC, the only remaining scope dependency is method visibility: "Foo::bar" may be visible in one scope but not in another. If in the future callable objects are limited to public methods, then callable types will become well-defined and can be used as property types. However, changes to visibility handling are not recommended as part of this RFC.

Improve the detection mechanism and level of undefined variables

Undefined variables are those that have not been read before they are read The variable being initialized. Accessing an undefined variable currently emits E_WARNING "Warning: undefined variable $varname" and treats the variable as null, but does not interrupt execution, allowing code execution to continue unabated, but possibly in an unexpected state.

Currently, some configurations can be used to allow PHP to generate error-level exceptions for undefined variables when executing, but this requires separate configuration. PHP should provide safer checks by default.

一般什么情况下会出现未定义变量的情况呢?

用法1

变量在某个分支中声明,比如在if中设置一个值。

1

2

3

4

5

6

7

if  ( $user -> admin )  {

   $restricted  =  false ;

}

 

if  ( $restricted )  {

   die ( '你没有进入这里的权限' ) ;

}

Copy after login

用法2

变量拼写错误:

1

2

$name = 'Joe';

echo 'Welcome, ' . $naame;

Copy after login

这种用法在1中也可能会发生:

1

2

3

4

5

6

7

8

9

if ($user->admin) {

   $restricted = false;

} else {

   $restrictedd = true;

}

 

if ($restricted) {

   die('You do not have permission to be here');

}

Copy after login

用法3

在循环中定义,但这个循环可能并没有执行:

1

2

3

4

5

6

7

while ($item = $itr->next()) {

 

   $counter++; // 定义变量

}

 

  // 这里调用了变量,但是很有可能并没有定义这个变量

echo 'You scanned ' . $counter . ' items';

Copy after login

解决方法

在这些分支之前提前定义好一个默认值。

对于第1种用法:

1

2

3

4

5

6

7

8

$restricted = true;

if ($user->admin) {

   $restricted = false;

}

 

if ($restricted) {

   die('You do not have permission to be here');

}

Copy after login

对于第3种用法:

1

2

3

4

5

6

$counter = 0;

while ($item = $itr->next()) {

   $counter++;

}

 

echo 'You scanned ' . $counter . ' items';

Copy after login

这样做的好处是消除了整个访问和使用这些未定义变量的后果,以及回退到引擎默认状态的用户态错误。这样我们提供了另一层保护,防止PHP程序发生了这种意外后继续运行。

这种更改也会让PHP引擎和JIT等方面不会那么复杂。

这个版本主要是针对PHP9.0的,在PHP8.2的还是警告,在以后会将这种行为提升到错误级别。

增加只读类

通过给类添加只读修饰符来声明只读类。

1

2

3

readonly class Test {

    public string $prop;

}

Copy after login

这样做会隐式地将类的所有实例属性标记为只读。此外,它将阻止创建动态属性。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

readonly class Foo

{

    public int $bar;

 

    public function __construct() {

        $this->bar = 1;

    }

}

 

$foo = new Foo();

$foo->bar = 2;

// 抛出错误,不能修改只读属性 Foo::$bar

 

$foo->baz = 1;

// 抛出错误:不能动态创建属性 Foo::$baz

Copy after login

可以通过增加#[AllowDynamicProperties]属性,可以不触发错误的情况下创建动态属性。

1

2

3

#[AllowDynamicProperties]

readonly class Foo {

}

Copy after login

一些限制:

由于是只读类,必须对属性声明类型:

1

2

3

4

5

readonly class Foo

{

    public $bar;

}

// 以上定义会产生错误。

Copy after login

不能使用静态属性:

1

2

3

4

5

readonly class Foo

{

    public static int $bar;

}

// 抛出错误: 只读属性不能声明静态类型

Copy after login

原文地址:https://phpreturn.com/index/a626a74a300dc5.html

原文平台:PHP武器库

版权声明:本文由phpreturn.com(PHP武器库官网)原创和首发,所有权利归phpreturn(PHP武器库)所有,本站允许任何形式的转载/引用文章,但必须同时注明出处。

推荐学习:《PHP视频教程

The above is the detailed content of What changes will be included in PHP8.2 (performance improvements, new features)!. 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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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

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

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.

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.

See all articles