What's new in PHP 8.2 The new features include, Changes, Deprecations and other changes
This article will go over the most recent features in PHP 8.2 in great detail. From its improvements and new features as well as minor deprecations .
As PHP 8.2 has entered the feature frozen state on July 19, 2022, it's likely that there will not add anything new to the feature list.
Excited? We're too.
Let's begin!
The PHP 8.2 release includes updates and features that are new. PHP 8.2
The first thing to do is look at every one of the PHP 8.2 features. It's a long checklist:
The new Read-only
classes
If you designate the class read-only
and all of its properties are able to benefit from the advantages of only reading.
feature. Therefore, declaring a classification as read-only
is similar to declaring every class property to be readonly
.
In the PHP 8.1 it was crucial to write this code to assign the property properties of every class to be "read-only"
:
Class MyClass
Imagine that with more possibilities. Today, using PHP 8.2 you can simply type:
Class that is read-only MyClassThe MyClass course MyClass is accessible only to readers.
Additionally, you can define abstract or final classes that are strictly read-only
. The sequence of keywords will make a difference.
abstract read-only class to {free no costead-only Class Dom{
Additionally, it is possible to designate the class as a read-only
class, with none of the properties. In effect, it prevents dynamic properties, but it allows children classes to define their property read-only
properties in a straightforward way.
Following, the next step is that only read-only
classes should only have properties that support types that can be defined in a typed manner. This is similar to declaring all of the properties to be only read-only properties.
You can make use of the mixed
type property even if you are unable to construct the property as specifically defined.
An attempt to design a class that is read-only
class that does not have a specific property type could result in fatal errors:
Read-only type $nope public fatal error: Read-only property Type::$nope must contain the word "type ... inside the line ...
Additionally, you are unable to make a declaration of readonly
on certain PHP attributes:
- Traits
- Interfaces
If you decide to mark one of these options only read-only, it
could result in an error when parsing.
interface that has read-only capabilities{ "estinyDestiny's Parse error syntax error, unexpected token "interface" Looking for "abstract" and "final" rather than "readonly" and "class" inside ... on the top of the page ...
Like all PHP keywords , the word readonly
keyword doesn't care about case.
PHP 8.2 is also a restriction on dynamic properties (more about this in the near future). There is no way to stop static properties being incorporated into classes. But, the addition of dynamic properties into the class that's a restricted to reading
class could lead to a fatal mistake.
Error: Property test that is read-only must be typed within ... on the first line ...
Let be True
, false
and null
to stand alone types
If you decide to classify these kinds in a way that they are counterfeit
or not-existent
or separate typesbut without mentioning that they belonged to the type union, it could cause fatal mistakes.
function is spam (){: eggs that are null, derived by the (){: that causes fatal errors: null can't be used to create a stand-alone type ... in the lines ... The error False cannot be used to construct an independent type ... within the line ...
To prevent this from happening to ensure that you are able to prevent this situation, and avoid this situation, PHP 8.2 adds support for this false
and non-null
in standalone types. By adding this feature, PHP's type system is more precise and full. It is now possible to specify the parameter, return and return types as well as the properties types precisely.
Furthermore, PHP still doesn't include an genuine
type, which seems to be a natural resemblance of this fake
type. PHP 8.2 fixes this issue and gives assistance to this genuine
type in addition. The type can't be coerced as it is in. fake
type works.
The True
and False
types are, in essence, similar to the types that PHP utilizes to create a type bool
type. To prevent redundancy it is not possible to declare the three types as a unison type. This can lead to end of compile-time.
Disjunctive Normal Form (DNF) Types
Disjunctive Normal Formula (DNF) is an established method of sorting Boolean expressions. It's a mixture of conjunctive terms , which is a Boolean expression as well as an OR that incorporates ands.
The RFC shows this by illustrating it in the following manner. The RFC assumes that the following terms for classes and interfaces are employed:
{Interface AInterface interface B{C C is an extension of the {interface AAlass interface. W{ implements Alass {X, which implements C, and implementsthe B class and implements C. {The class Z extends Y and implements C{C.
By using DNF types, you're in a position to create declarations of types to specify the parameters, properties, as well in return values, such as:
Accepts any object that implements A and B//or objects that implement D (A&B)(A&B)D /It will accept any object which implements C and // or that is an element of X using D (or nullC/(X&D)null (X&D)null // It will accept any object that has three elements in A B. D which can be an integer or null. (A&B&D)|int|null
Sometimes, these properties could not be displayed when they are in DNF form. If this is the case, making the properties DNF may result in errors in the parsing. But, it is possible to write the words according to the procedure according to the following:
A&(B D) * Rewriteable using (A&B)(A&D) A|(B&(D W)) /Rewriteable as A(B&D)(B&W)null
You should note that each segment within the DNF type should be distinctive. As an example, declaring (A&B)(A&B)(B&A)
is invalid since the two ored segments are in fact the same.
For this segment, the only subsets that belong to an additional segment aren't able to be utilized. This is because the superset already has the capability of containing all subsets. Therefore, it's not required to use DNF.
Redact Sensitive Parameters are used in Traces that are back Traces
A trace from a stack won't stop the execution or operation of the application. The majority of stack trace operate in the background and is captured in a quiet manner to later be examined in the event of a necessity.
The HTML0 RFC concept gives 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 lets you determine sensitive parameters with the newly added sensibly parameter
attribute. Any parameter marked with sensitive labels are not found within the tracebacks. It means that you're capable of using them in combination with the services of an outside party.
Here's a simple 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 tried before the mysqli_query()
function with the possibility of ejecting information from users for the parameter-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. It will ensure that the MySQLi query will be made accessible and connected (if there is any parameters) then executed by the software. If the query was successful it will produce an mysqli_result
object. If it doesn't succeed, it'll give an error code of True.
.
The RFC suggestion is a straightforward but powerful framework
foreach ($db->execute_query('SELECT * FROM user WHERE name LIKE ? and type_id (? ? ) (", "$name" $type1 and $type2) as"$row" as) print_r($row );
Fetch and return an Enum
Properties with const
Expressions
The main reason for this feature is because it's difficult to make use of enum
objects in specific places such as array keys. If this is the case, you'll need to apply exactly the same values to an example of the an enum
instance in order to use this feature.
Allowing fetching of the Enum
properties in places where the objects of the enum
objects aren't can make the process much easier.
It is a sign that the current code is being implemented:
Const C = self = B->value = self: B[
To protect yourself And to be safe. To be safe To be protected, this RFC is also a supporter for operators that are nullsafe ?
.
Accept Constants in Traits
PHP can be used to reuse code . This is known as Traits. Traits can be used to reuse of code between classes.
At present, Traits are restricted to defining the properties and methods, and there are no constants. It is not possible to determine the invariants needed of Traits within the Trait's own. In order to overcome this issue, you need to define constants either in the class that composes the Trait or in the interface that is implemented by its composing class.
RFC proposes the definition of constants within Traits. These constants can be defined in the exact manner as they are defined in the classes of constants. This sample straight from RFC can clarify the issues regarding its use
trait Foo$flags & self::FLAG_3
Constants used by Traits are also incorporated in the composition of the class. This is the same as Traits methods and property definitions. Furthermore, they can be restricted in the same way as properties of Traits. The RFC this feature is being proposed although a great beginning, needs further work to fully define the feature.
The precautions contained in PHP 8.2
It is now possible to go through the entire list of changes made of PHP 8.2. It's not as comprehensive in comparison to the latest improvements:
Do you want to know how we managed to increase the number of visits we get to 1000 percent?
Join more than 20,000 other users to get our weekly newsletter with insider WordPress tricks!
Deprecate Dynamic Properties (and New #[AllowDynamicProperties]
Attribute)
class Post public int $pid;post = new Post();the name of the post is ''.
Here you'll be able to see that post class does not have a called property. Post
class doesn't have a named
property. As PHP includes dynamic properties and dynamic properties, you are able to declare the class in a different way from declarations of the class. Most important is probably the most important and most important.
Dynamic properties may cause unexpected errors and behavior to appear in code that you create. If, for instance, you do a wrong thing when declaring a property of one of your classes within a class that's not part of it, it's easy to forget about it, especially in trying to find out the cause of the error within the class.
From PHP 8.2 and onwards, dynamic properties are eliminated. Setting a value for an attribute in a class that has not been registered can trigger an error message in the event that the value for the property has been modified. {lass Foo"new" Foo // Discontinued The dynamic property which Foo generated the value for the value of $bar was removed and is not supported.$foo->bar = 1;/ No deprecation notice The dynamic property exists already exist. $foo->bar = 2;
Additionally, from PHP 9.0 or later, the same settings will cause an 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 reached via the __get()
or the sets()
PHP magic methods don't count as dynamic properties. That means they don't result in an error message that says deprecation has occurred.
Removing Partially Supported Callables
Another PHP 8.2 change, albeit with less impact and is to remove callables that are not supported in part.
The above callables are considered to be not fully available since it is not possible to get them directly via callable()
. You can only get to them with the call_user_func($callable)
function. Callables that are available are not very 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 any attempt to invoke the functions -- for example, through calling the function call_user_func()
or array_map()
functions -- - will produce an error message which states that the function cannot be used.
The first RFC contains solid arguments that support the choice
"self::method"
"Foo::bar"Closure::fromCallable()
According to the initial RFC that was released, it is stated that the is_callable()
function and the callable
type will continue to recognize the calls made by these types but in a manner that doesn't pose an issue. This is except for the time that support for these types is completely removed from PHP 9.0 beginning from this date onwards.
In order to ensure there's any confusion to avoid confusion, the scope of the deprecation notice will be increased by a newly created RFC -- which contains these exemptions.
It's a good thing to see PHP moving towards having a clear kind of type that's a callable
type.
It's not advised to make use of code #utf8_encode()
and decode utf8()
Functions
Built-in PHP functions UTF8_encode()
and decode_utf8()
convert strings encoded by ISO-8859-1 ("Latin 1") to UTF-8 and vice versa.
The names of their respective codes suggest that they're more commonly used than their implementation allows. "Latin 1" is one of the most well-known codes "Latin 1" Codings can be misinterpreted by other codes, like as"Windows Code Page 1252. "Windows Code Page 1252."
In addition, you'll often encounter Mojibake in instances when these tools aren't able to change the right string. The absence of warnings in the event of an errormakes it hard to recognize these types of functions, especially when they are in plain text.
It's PHP 8.2 deprecates both #utf8_encode()
and the decode()
functions. If you use the functions, you'll be greeted by these warnings about removal:
Deprecated: Function UTF8_encode() is no longer supported.Deprecated The UTF8_decode function() is eliminated from the list of functions.
Deprecate $
String Interpolation
PHP lets you insert variables inside strings by using double quotes ( "
) and heredoc ( ) using a range of methods:
- Directly embedding variables directly in
"$foo"
- Braces that are outside of the parameters (i.e.
"$foo"
- Braces that follow the dollar sign -
"$foo"
- Variable variables ---
"$expr"
-- equivalent to using(string)"$expr" -- equivalent to using (string)
Three options are listed above. all have advantages and disadvantages The two options with the most drawbacks are a bit more complicated and have inconsistent syntax. It is PHP 8.2 deprecates the last two options of string interpolation.
Avoid interpolating strings using this method In the future, you should avoid interpolating strings by using this method
"Hello, $world! " {"Hello, $world "*Deprecated Use of the term "$" in strings is not recommended"Hello"Hello, $(world)! " {*Deprecated: ". It is not recommended to include $ with $(variable variables) in string is not recommended.
Starting with the release of PHP 9.0 These outdated deprecations are updated in order to generate errors.
Deprecate mbstring Functions for Base64/QPrint/Uuencode/HTML Entities
The mbstring (multi-byte string) functions allow us to use Unicode, HTML entities, and other other encodings for text that have been utilized for quite a while.
However, Base64, Uuencode, as and QPrint do not encode text however they are at the core of these functions, mostly because of the motives for the previous versions. PHP can also be an alternative implementation of these encryptions.
For HTML-based entities PHP includes built-in functions like htmlspecialchars()
and HTMLentities()
-for taking care of these issues better. In this case, opposed to Mbstring the functions convert into
. >
and and
characters to HTML entities.
In keeping the above to mind In PHP 8.2 will be discontinuing the use of Mbstring for this encoder (the labels have a case-sensitive):
- BASE64
- UUENCODE
- HTML-ENTITIES
- HTML (alias for HTML-ENTITIES)
- Quoted-Printable
- Qprint (alias of Quoted Print-Able)
Starting with PHP 8.2 from then on when mbstring is used to encode or decode, every one of these options will be subject to a notice of deprecation. PHP 9.0 will cease support for mbstring on the encoders mentioned above completely.
Some minor changes are also implemented in PHP 8.2
It is also possible to look over the PHP 8.2's slight changes, such as the removal of functions and features.
Eliminate the support for mysqli in the libmysql library.
At present, PHP allows both mysqli
and mysql PDO
drivers to communicate with mysqlnd
and mysql in addition to mysql and the libmysql
libraries. But, the most popular and widely used driver for PHP from the time PHP 5.4 is 5.4 has been mysqlnd
.
Both drivers have many benefits and drawbacks. The removal of support for one driver -- or the ideal solution is eliminating mysql off this list
because it's not an official -can make PHP's code easier to write unit tests.
To justify this benefit to justify mysqlnd's use I'd want to highlight that the RFC provides a variety of advantages derived from mysqlnd
:
- It's integrated into PHP
- Provides quality-of-life functions (e.g.
get_result()
) - The values are numerical and can be retrieved with the help of PHP native types
- The library's functionality does not require an additional library.
- Optional plugin features
- Supports asynchronous queries
The RFC contains a number of benefits that come with this database
including:
- It is possible to connect automatically (
mysqlnd
doesn't specifically allow this since it can be used) - There is a possibility of using LDAP as well as SASL authenticating methods (
mysqlnd
may add this feature very soon)
Additionally, the RFC that lists various negatives that are associated with the database created with libmysql
which is incompatible with PHP memory model, many errors in testing and leaks of memory, as well as different functionality among versions, etc.
As a result, PHP 8.2 was unable for building mysqli
against mysql's libmysql
.
If you'd like to extend functions that only work in conjunction with the MySQL library,
it is necessary to integrate it into mysqlnd
by way of an improvement request. Additionally, it is not possible to connect by auto.
Locale-Independent Case Conversion
In this case, say you choose "Turkish" and "Kazakh" languages as you first installed Linux and then you'll see you are able to use toupper('i')
to convert it to higher case, which will produce the punctuated capital I (U+0130, I
).
PHP 8.0 has prevented this issue by changing its default locale to "C," unless the user alters it applying "setlocale"()
.
PHP 8.2 is even more advanced in eliminating the entire sensitivity to locales in the converters for case. The RFC is mostly a modification to strtolower()
, strtoupper()
, and similar functions. Check out the RFC to find a complete list of the functions affected.
If you'd prefer to make use of localized case conversion, you can employ the mb_strtolower()
.
Random Extension Improvement
PHP intends to modify the random function of PHP.
At present, PHP's random function heavily depends upon its Mersenne Twister state. The state, however, is not stored within PHP's global databaseThere is no method for a user to have access to the state. The addition of randomization features in the beginning of the seeding process along with the planned application would disrupt the code.
Maintaining such code can be much more difficult when your code relies on outside packages.
Therefore, PHP's present random function can't replicate random numbers in a homogeneous manner. In addition, it is unable to verify statistical consistency of random number generators like TestU01's Crush as well as BigCrush. Mersenne Twister's 32-bit limitation further creates more difficulties.
Therefore, PHP's built-in functions like shuffle()
, str_shuffle()
, array_rand()
-- aren't recommended for those looking to secure the digital random number. To protect against this you must create an entirely new function that makes use of an algorithm known as random_int()
or similar functions.
However, several issues with the RFC were brought up after the vote had started. The setback forced PHP PHP team to write each issue within an independent RFC that included a vote on each issue. The PHP team will decide to move forward until they've come to an agreement.
Additional RFCs for PHP 8.2
PHP 8.2 comes with numerous improvements as well as small changes. Below, we'll discuss them as well as provide links to further information:
- A new
curl_upkeep
function : PHP 8.2 includes this function to its Curl extension. This function is a call to curl_easy_upkeep(), which is thecurl_easy_upkeep()
function in the libcurl library, which is the basis C library that it is the PHP Curl extension uses. - New
memory_reset_peak_usage
function: This function resets the peak memory usage returned by thememory_get_peak_usage
function. This function is useful when you're performing the same thing over and over again and need to monitor each process's max memory consumption. - Modifications to the no-capture (
/n
) inpreg_*
functions in regex. By using () metacharacters in regex the()
metacharacters indicate a capturing group. This means that all matches to an expression inside the bracket are returned. PHP 8.2 includes the modifier no-capture (/n
) to prevent this behaviour. - Iterator_*() family accept every iterator's names. () Family accepts all iterables as of today as of today. PHP Iterator's*() family will only take Traversables (i.e. Plain arrays are not which are supported). This is a limitation that isn't necessary given the options the possibilities, and this RFC resolves the issue.
Summary
PHP 8.2 builds on the massive improvements that were made in PHP 8.0 as well as PHP 8.1 which isn't an easy feat. Our top picks for the most intriguing PHP 8.2 highlights include unique independent types, read-only properties, as well as numerous performance enhancements.
Bookmark this blog for the next time you need information.
Which PHP 8.2 features you like most? Which deprecations do that you dislike the least? Please share your thoughts in our discussion forum by posting your comments!
Costs, time and time savings , and boost website performance.
- Support is accessible 24/7. Help from WordPress hosting experts, 24/7.
- Cloudflare Enterprise integration.
- International reach thanks to 34 data centers spread across the globe.
- Optimization through our application's integrated Performance Monitoring.
Article was first seen on this site
Article was first seen on here