What's new with PHP 8.2 It's new features, Changes, Deprecations and changes

Aug 11, 2022

This article will cover the latest features of PHP 8.2 with great depthFrom its new features and enhancements to minor deprecations .

As PHP 8.2 has entered the feature freezing on July 19 2022, it's most likely that there will not be anything new added to the list.

Excited? We're too.

Let's begin!

This PHP 8.2 release comes with enhancements and new features. PHP 8.2

The first step is to look at every one of the new PHP 8.2 functions. It's a long checklist:

New Read-only classes

If you designate the class read-only, all its properties will inherit the benefit of reading only. feature. So, declaring a classification in a read-only manner is similar to declaring every class property as readonly.

For PHP 8.1 it was essential to write this code to set the properties of every class as read-only:

class MyClass

Imagine this with additional options. Now, with PHP 8.2 it's possible to simply write:

Read-only class MyClassThe MyClass class MyClass is only accessible to readers.

Additionally, you can define abstract or final classes strictly read-only. The sequence of keywords does not matter.

abstract read-only class for free {Read-only Class Dom{

It is also possible to declare the class as a reading-only class, which has no properties. In effect, it prevents dynamic properties however it permits children classes to define their property read-only properties in a straightforward manner.

Following, next, read-only classes can only contain properties with types that can be specified as typed. This is exactly like declaring each of the properties as only read-only properties.

You can make use of this mixed type property if you're unable to create the property as specifically defined.

A plan to create a readonly class without a specified property type could result in fatal errors:

Read-only type $nope public fatal error: Read-only property Type::$nope must contain the word "type ... within the line ...

In addition, you cannot declare readonly on certain PHP attributes:

  • Traits
  • Interfaces

If you attempt to declare one of these options as readonly will produce a parse error.

interface with read-only capabilities {DestinyDestiny's Parse error syntax error, unanticipated token "interface" Looking for "abstract" as well as "final" instead of "readonly" and "class" inside ... at the page ...

Similar to all PHP keywords , the keyword readonly keyword doesn't care about case.

PHP 8.2 also prohibits dynamic properties (more about that in the future). There is no way to prevent static properties from being incorporated into classes. But, the addition of dynamic properties into a class that is read-only class may result in a fatal error.

Error: property read-only Test must have type in ... on the beginning of the line ...

Let True, false and null as stand-alone types

If you attempt to label these types as fake or non-existent or standalone types -- without the fact that they belonged to a type union this could cause fatal mistakes.

function is spam (){: null eggs derived from the function (){: fatal error: Null can't be used as a standalone type ... in the line ... Error: false cannot not be used to create a stand-alone type within ... within line ...

To stop this happening To be able to avoid this situation, and avoid this scenario, PHP 8.2 adds support to make use of this false and not-null as standalone types. By adding this feature, PHP's system of types has become more precise and full. You can now specify the parameter, return and return types as well as the property types in a precise manner.

Additionally, PHP still doesn't include an true type, which seems to be a natural resemblance of the fake type. PHP 8.2 corrects this and provides assistance to this authentic type in addition. This type isn't able to be coerced the way it has done in. fake type works.

The true and False types are, in essence, the same type that PHP uses as an type bool type. To prevent redundancy it is not possible to declare the three types together in an unison type. This can lead to end of compile-time.

Disjunctive Normal Form (DNF) Types

Disjunctive Normal Formula (DNF) is a standardized way of sorting Boolean expressions. It's a mix of conjunctions , which is a boolean expression, and is an OR that includes ands.

The RFC illustrates this in the following way. It assumes the following terms for interfaces and classes are used:

{interface AInterface A interface B{{ C C extends the interface A{class W implements A{class X, which implements {Bthe B class  and implements C. {BClass Z extends Y and implements C{C .

By using DNF types, you are in a position to create declarations of type to define parameters, properties as well as return values  like:

Accepts any item that implements A and B// or an object that implements D (A&B)(A&B)D // It will take any object which implements C, // or that is a subset of X with D or nullC/(X&D)null (X&D)null // Will accept any object that implements three elements of A B, D either an integer, or the null. (A&B&D)|int|null

Sometimes, these properties could not be visible in DNF form. In this case, making the properties DNF could produce errors in the parsing. However, you are able to write the words in the following manner as follows:

A&(B D) * Rewriteable with (A&B)(A&D) A|(B&(D W)) // Could be rewritten as A(B&D)(B&W)null

You should note that each segment in a DNF type must be unique. As an example, declaring (A&B)(A&B)(B&A) is not valid since both ORed segments are logically the same.

To this segment that are only subsets of another segment can't be used. This is because the superset is already capable of containing all subsets. Thus, it is not necessary to utilize DNF.

Redact Sensitive Parameters are used in Traces that are back Traces

Tracking slow WooCommerce transactions through the  APM tool.
The monitoring of slow WooCommerce transactions making use of APM.

The trace of a stack won't stop the execution or operation of the software. The majority of stack trace work in the background and can be recorded in a silent mannerto later be inspected in the event of a need.

The HTML0 RFC proposition offers an example:

separate ->connect()
PDOException: SQLSTATE[HY000] [2002] No such file or directory in /var/www/html/test.php:3 Stack trace: #0 /var/www/html/test.php(3): PDO->__construct('mysql:host=loca...', 'root', 'password') #1 main

PHP 8.2 permits you to identify sensitive parameters with the newly added sensible parameter attribute. Any parameter marked with sensitive labels is not listed in the backtraces. This means that you are capable of using them in conjunction with any service from a third party.

Here's a quick example using a single sensitive parameter

When you generate a backtrace, any parameter with the \SensitiveParameter attribute will be replaced with a \SensitiveParameterValue object, and its real value will never be stored in the trace. The SensitiveParameterValue object encapsulates the actual parameter value -- if you need it for any reason.

New mysqli_execute_query Function and mysqli::execute_query Method

Have you ever used the mysqli_query() function with possibly ejecting user information to run the parameters-based MySQLi query?

PHP 8.2 makes running parameterized MySQLi queries easier with the new mysqli_execute_query($sql, $params) function and mysqli::execute_query method.

Essentially, this new function is a combination of mysqli_prepare(), mysqli_execute(), and mysqli_stmt_get_result() functions. With it, the MySQLi query will be made ready and connected (if there are any parameters), and executed within the program. If the query was successful it will produce the mysqli_result object. If it fails, it'll give the value False..

The RFC proposal gives a simple and powerful model

foreach ($db->execute_query('SELECT * FROM user WHERE name LIKE ? and type_id (? ? ) (", "$name" $type1 and $type2) as $row) print_r($row);

Fetch an Enum Properties using const Expressions

The primary reason behind the new functionality is because it's not possible to make use of enum objects in certain places such as array keys. If this is the case, you'll need to apply exactly the same values as an instance of the enum instance in order to utilize this feature.

Enabling fetching of the enum properties in places where the enum objects can't be found in could make this process easier.

It is a sign that the current code is in effect:

Const C = self::B->value = self: B[

For your safety, and just for the sake of it. To be safe To be safe, this RFC is also a supporter for operators that are nullsafe ?.

Accept Constants in Traits

PHP can be used to reuse code , referred as Traits. Traits are perfect for reuse of code across classes.

In the moment Traits are restricted to defining methods and properties and there are no constants. It is not possible to identify the necessary invariants from Traits in the Trait's own. To get around this limitation you must create constants in the composing class of the Trait or in an interface implemented by its composing class.

RFC proposes to define constants within Traits. These constants can be defined in the exact manner as the way you define the class of constants. This example straight from the RFC can clarify the issues surrounding its usage

trait Foo$flags & self::FLAG_3

Constants used by Traits can also be included into the composition definition of the class, which is identical to Traits' method and property definitions. Additionally, they are restricted in the same way as properties of Traits. In the RFC the proposed feature, while a fantastic start, requires further development to fully define the feature.

Precautions in PHP 8.2

It is now possible to look through all the changes made of PHP 8.2. This list isn't quite large as it is with the latest improvements:

Do you want to know the steps we took to boost the number of visitors we receive by 1000 per cent?

Join over 20,000 others to get our weekly newsletter with insider WordPress tips!

Deprecate Dynamic Properties (and New #[AllowDynamicProperties] Attribute)

class Post public int $pid;post = new Post();the post's name is ''.

This is where you will notice that the post class does not have a called property. Because PHP includes dynamic properties and dynamic properties, you can declare it in a distinct manner from the declarations for the class. The most important that is perhaps the only -- and most important.

Dynamic properties can cause unanticipated bugs and behaviours to show up in the code that you write. For instance, if you commit a mistake when declaring a property of one of your classes in a class that's not part of it, it's very easy to forget about it, especially in trying to find out the cause of errors within the class.

Beginning with PHP 8.2 and onwards, dynamic properties are deleted. Setting a value for a property in a class that has not been registered will trigger a deprecation notice when the property value is changed. {class Foo $foo = new Foo // Deprecated: This dynamic property that Foo created the value of $bar has been removed and is not supported.$foo->bar = 1;/ No deprecation warning The dynamic property exists already existence. $foo->bar = 2;

In addition, as of PHP 9.0 and onwards using the same setting will produce the ErrorException error.

If your code is full of dynamic properties -- and there's a lot of PHP code that is -- and if you want to stop these deprecation notices after upgrading to PHP 8.2, you can use PHP 8.2's new #[AllowDynamicProperties] attribute to allow dynamic properties on classes.

#[AllowDynamicProperties] class Pets class Cats extends Pets // You'll get no deprecation warning $obj = new Pets; $obj->test = 1; // You'll get no deprecation warning for child classes $obj = new Cats; $obj->test = 1;

As per the RFC, classes marked as #[AllowDynamicProperties], as well as their child classes, can continue using dynamic properties without deprecation or removal.

You should also note that, in PHP 8.2, the only bundled class marked as #[AllowDynamicProperties] is stdClass. Additionally, properties that can be accessed through __get() or the __set() PHP magic methods aren't considered to be dynamic properties. This means that they won't cause the error message that says deprecation has occurred.

Removing Partially Supported Callables

Another PHP 8.2 change, albeit that has a lesser impact, is to remove callables that are not supported in part.

The above callables are classified as not fully supported because you cannot access them directly using callable(). You can only get to them with the call_user_func($callable) function. Callables that are available is not long.

"self::method" "parent::method" "static::method" ["self", "method"] ["parent", "method"] ["static", "method"] ["Foo", "Bar::method"] [new Foo, "Bar::method"]

Since PHP 8.2 and onwards, all attempts to invoke these functions -- like through calling the function call_user_func() or array_map() functions -- - will produce an error message that states the function cannot be used.

The first RFC contains solid arguments to support this choice:

"self::method"
"Foo::bar"Closure::fromCallable()

According to the initial RFC, the is_callable() function and the callable type will continue to recognize calls in these types in a way that isn't an issue. The exception is when support is removed completely from PHP 9.0 beginning from this point onwards.

To ensure that there is no confusion, the deprecation notice's scope is extended by an new RFC -- and includes these exceptions.

It's good to observe PHP moving towards having a clear type that is a callable type.

It is not advised to utilize #utf8_encode() and decode utf8() Functions

Inbuilt PHP function UTF8_encode() and decode_utf8() convert strings encoded with ISO-8859-1 ("Latin 1") to and from UTF-8.

Their names, however, suggest that they're more commonly used than their implementation allows. "Latin 1" is a well-known encoding "Latin 1" Encodings are often misinterpreted with other codes, such as"Windows Code Page 1252. "Windows Code Page 1252."

In addition, you'll often see Mojibake in instances when these tools aren't able to transform the proper strings. The absence of warnings in the event of an error, making it difficult to identify these types of functions, particularly in an otherwise clear text.

It is PHP 8.2 deprecates both #utf8_encode() and the utf8_decode() functions. If you use the functions, you'll get greeted by these warnings about deprecation:

Deprecated: Function utf8_encode() is no longer supported.Deprecated The function UTF8_decode() has been removed from used.

Deprecate $ String Interpolation

PHP lets you embed variables within strings using double quotes ( ") and heredoc ( ) using a range of methods:

  1. Directly embedding variables directly into "$foo"
  2. Braces that are outside of the variables -- "$foo"
  3. Braces that follow the dollar sign -- "$foo"
  4. Variable variables --- "$expr" -- equivalent to using (string) $expr

The three options listed above each have advantageous and drawbacks, whereas the latter two have complex and inconsistent syntax. The PHP 8.2 deprecates the last two options of interpolation of strings.

Beware of interpolating strings with this method In the future, avoid interpolation of strings using this method:

"Hello, $world! " {*Deprecated: "*Deprecated: using the word "$" within strings is not recommended"Hello Hello, $(world)! " {*Deprecated: ". Deprecated: including $ using $(variable variables) in strings is not recommended.

Beginning with the release of PHP 9.0 These deprecations are upgraded in order to generate errors.

Deprecate mbstring Functions for Base64/QPrint/Uuencode/HTML Entities

The mbstring (multi-byte string) functions allow us to work with Unicode, HTML entities, and various other text encodings that have been used for a long time.

However, Base64, Uuencode, as and QPrint do not encode text but remain a component of these functions mostly because of the motives behind the old versions. PHP is also an independent implementation of these encryptions.

For HTML-based entities PHP comes with built-in functions -- such as htmlspecialchars() and HTMLentities() -for handling these better. As an example, as opposed to Mbstring, these functions translate into. > and and characters into HTML entities.

In keeping the above to mind In PHP 8.2 is discontinuing the use of mbstring in these encoders (the labels are case-sensitive):

  • BASE64
  • UUENCODE
  • HTML-ENTITIES
  • HTML (alias for HTML-ENTITIES)
  • Quoted-Printable
  • qprint (alias of Quoted-Print-Able)

Beginning with PHP 8.2 from then on when mbstring is used to encode or decode, each of these options will trigger a deprecation notice. PHP 9.0 will end the support for mbstring for the encoders mentioned above completely.

Minor changes are also made in PHP 8.2

It is also possible to look over the PHP 8.2's minor changes, including the elimination of functions and features.

Get rid of the support for mysqli in libmysql.

At present, PHP allows both mysqli and mysql PDO drivers to interface together with mysqlnd as well as mysql as well as mysql and libmysql libraries. But, the most popular and standard driver in PHP since PHP 5.4 has been 5.4 is mysqlnd.

Both drivers have many advantages and disadvantages. The removal of support for either of them -- and, ideally removing mysql from the list since it's not the standard -can make PHP's code easier to write unit tests.

For the purpose of justifying this advantage to support mysqlnd I would like to point out that the RFC lists a range of benefits from mysqlnd:

  • It's integrated with PHP
  • Provides quality-of-life functions (e.g. get_result())
  • Numeric values returned by with the help of PHP native types
  • The library's functionality does not require any external library.
  • Optional plugin functions
  • Supports asynchronous queries

The RFC includes a few benefits of the database which include:

  • There is a way to automatically connect ( mysqlnd doesn't explicitly allow this because it could be utilized)
  • It is possible to use LDAP as well as SASL authenticating techniques ( mysqlnd might add this feature very soon)

In addition there is the RFC lists a variety of disadvantages associated with the database built with libmysql -- incompatibility with PHP memory model, many errors in testing and leaks of memory, along with different functions between versions, and so on.

As a result, PHP 8.2 removed support to build mysqli against mysql's libmysql.

If you'd like to extend functions that only work with the libmysql library it's necessary to explicitly add it to mysqlnd as an enhancement request. Also, you cannot connect automatically.

Locale-Independent Case Conversion

As an example, suppose you chose "Turkish" and "Kazakh" languages, when you first installed Linux and you'll find that you can use toupper('i') to obtain its equivalent in uppercase will result in the punctuated capital I (U+0130, I).

PHP 8.0 prevented this issue by switching its default locale from "C," unless the user changes it by using the setlocale().

PHP 8.2 goes even further in completely removing the sensitivity to locales from the convertors for case. The RFC is mainly a change to strtolower(), strtoupper(), and similar functions. Go through the RFC to find a complete list of the functions affected.

As an alternative, if you'd like to use localized case conversion , you can employ the mb_strtolower().

Random Extension Improvement

PHP is planning to modify its random functions.

At present, PHP's random function is heavily dependent upon its Mersenne Twister state. The state, however, is not stored within PHP's global databaseThere is no way that a user would be able to access it. The addition of randomization features in the beginning of the seeding process along with the planned application would break the programming.

Maintaining such code can be much more difficult when your code relies on external package.

So, PHP's current random function is unable to reproduce random numbers in a uniform manner. Even, it fails to test statistical consistency in random number generators, like TestU01's Crush and BigCrush. Mersenne Twister's 32-bit limitation further makes this even more difficult.

So, using PHP's built-in functions -- shuffle(), str_shuffle(), array_rand() -- aren't recommended for those who want to safeguard the cryptographic random number. For these situations, it's required to design a completely new function which uses an algorithm called random_int() or similar functions.

But, several issues with the RFC were raised after the voting had begun. The setback forced PHP PHP team to write down all the issues in an independent RFC that included a vote on each issue. The PHP team will decide to move forward until they've reached an agreement.

Additional RFCs to PHP 8.2

PHP 8.2 comes with numerous new features as well as minor changes. We'll go over them below and provide links to more info:

  1. A new curl_upkeep function : PHP 8.2 adds this function in its Curl extension. The function calls on the curl_easy_upkeep() function in the libcurl library, which is the base C library that it the PHP Curl extension uses.
  2. New memory_reset_peak_usage function: This function resets the peak memory usage returned by the memory_get_peak_usage function. It can be handy for when you're performing the same thing over and over again and need to track each execution's memory usage maximum.
  3. Modifications for no-capture ( /n) in preg_* functions in regex. by using () metacharacters in regex, the () metacharacters indicate a capturing group. That means all matches for the expression within the bracket are returned. PHP 8.2 adds the no-capture modifier ( /n) to prevent this behaviour.
  4. Iterator_*() family accept every iterator names.() family accept all iterables as of today the PHP iterator_*() family only will accept the Traversables (i.e. there are no plain arrays accepted). This restriction is unnecessary the options the possibilities, and this RFC solves the problem.

Summary

PHP 8.2 expands on the huge improvements made in PHP 8.0 and PHP 8.1 that isn't an easy feat. Our top choices for the most exciting PHP 8.2 highlights are unique independent types, read-only properties, as well as numerous performance enhancements.

Keep this blog post for the next time you need information.

Which PHP 8.2 features you like the most? Which of the deprecations you find least preferred? Please share your thoughts in our discussion forum by posting your comments!

Costs, time and time savings and improve site performance

  • Support is always available 24/7. help from WordPress hosting experts, 24/7.
  • Cloudflare Enterprise integration.
  • Global reach with 34 data centers across the globe.
  • Optimization through our application's integrated Performance Monitoring.

Article was first seen on here