What’s New in PHP 8.2 – Changes and Updates

php 82 changes and updates

PHP 8.2 is built on the new base laid out in PHP 8.0 in addition to PHP 8.1. With PHP 8.2 release date being released, we’ll look at the PHP 8.2 changes in detail, from the enhancements and new features to minor and deprecations, we’ll review everything.

Since PHP 8.2 entered its feature freeze on the 19th of July 2022, we can anticipate nothing new to add to this list.

 

New Features and Improvements in PHP 8.2

With PHP latest version, a lot of hosting companies offer the latest version once you buy a VPS hosting account to take your website to the next version with PHP 8.2 new features. But what is added in the PHP latest version?

 

Readonly Classes

Readonly properties were added within an account once you buy VPS server with PHP 8.2 or you can update your current version. This RFC builds upon them and includes syntactic sugar, making all class properties read-only all at once. Instead of writing:

class Post

{

public function __construct(

public readonly string $title,

public readonly Author $author,

public readonly string $body,

public readonly DateTime $publishedAt,

) {}

}

Now you can write:

readonly class Post

{

public function __construct(

public string $title,

public Author $author,

public string $body,

public DateTime $publishedAt,

) {}

}

 

Functionally creating a class as read-only is exactly similar to making each property read-only. However, it also blocks dynamic properties from being added to the class:

$post = new Post(/* … */);

 

$post->unknown = ‘wrong’;

 

It is important to note that you are able to extend the read-only class if the child class is read-only also.

 

Deprecate dynamic properties

We’d consider this to be an improvement to the PHP 8.2 changes; however, it may be a bit painful. Dynamic properties will be removed in PHP 8.2 and will generate an ErrorException in PHP 9.0:

class Post

{

public string $title;

}

 

// …

 

$post->name = ‘Name’;

Remember that classes that implement __get and __set will continue to function according to the intended way:

class Post

{

private array $properties = [];

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

{

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

}

}

 

// …

 

$post->name = ‘Name’;

 

New Random Extension

PHP 8.2 includes a brand new random number generator, which fixes many of the issues with the old one, makes it more efficient and secure, simpler to maintain and doesn’t depend on the global state, thereby eliminating many difficult-to-find bugs when making use of PHP 8.2 performance of random function.

There’s a brand new class called Randomizer that accepts an engine for randomization. You can now alter that engine to suit the requirements of your business. For instance, you can distinguish between a test and a production environment.

$rng = $is_production

? new Random\Engine\Secure()

: new Random\Engine\Mt19937(1234);

 

$randomizer = new Random\Randomizer($rng);

$randomizer->shuffleString(‘foobar’);

 

false, true, or null false as stand-alone types

With the PHP 8.2 released date it introduces three new types or something similar to it. We’ll stay clear of the rabbit hole of type security in this blog. However, technically true, false, and null can be considered valid types in their own right. The most common examples are PHP’s built-in function, in which false is the return type in the event that errors occur. For instance, in file_get_contents:

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

 

Prior to PHP 8.2, it was possible to previously use false in conjunction with other types to form the union type; however, it is possible to use it as a stand-alone type, too:

function alwaysFalse(): false

{

return false;

}

 

This is also true in the case of null and true.

 

Disjunctive Normal Form Types

DNF types let us combine intersection types and union types. They follow an unwritten rule for combining intersection and union kinds; the intersection type has to be separated by brackets. In reality, it appears like this:

function generateSlug((HasTitle&HasId)|null $post)

{

if ($post === null) {

return ”;

}

 

return

strtolower($post->getTitle())

. $post->getId();

}

In this case, (HasTitle&HasId)|null is the DNF type.

This is a wonderful PHP 8.2 performance enhancement, particularly because it means we now use nullable intersection types. This is perhaps the most significant use case of this new feature.

 

Constants in the traits

It is now possible to use constants in the following traits:

trait Foo

{

public const CONSTANT = 1;

 

public function bar(): int

{

return self::CONSTANT;

}

}

It isn’t possible to access the constant through the trait’s name within the trait or inside it.

trait Foo

{

public const CONSTANT = 1;

 

public function bar(): int

{

return Foo::CONSTANT;

}

}

 

Foo::CONSTANT;

 

You are able to access the constant through the class that utilizes the trait, provided that it’s publicly available:

class MyClass

{

use Foo;

}

 

MyClass::CONSTANT; // 1

Redact Parameters from Back Tracks

The most common practice in any codebase is to report mistakes in production to a system that keeps track of the errors and informs developers when something is wrong. This is usually done by sending stack trace data via wire to a third-party service. However, there are instances where these stack trace tracks can contain sensitive data such as passwords, environment variables, or usernames.

PHP 8.2 lets you identify these “sensitive parameters” with an attribute so that you don’t have to be concerned about them appearing in your stack trace when there’s a problem. Here’s an example from RFC:

function login(

string $user,

#[\SensitiveParameter] string $password

) {

// …

throw new Exception(‘Error’);

}

 

login(‘root’, ‘root’);

 

Fetch Properties for Enums within Const expressions

This RFC proposes using the ->or the? to retrieve properties of enums within constant expressions. The principal reason behind the change would be to permit the fetching of names and values of enums in locations where enum objects can’t be allowed, for example, array keys

This signifies that the following code is valid now:

enum A: string

{

case B = ‘B’;

const C = [self::B->value => self::B];

}

Return type changes for DateTime::createFromImmutable() and DateTimeImmutable::createFromMutable() breaking

The methods used in the past were as follows:

DateTime::createFromImmutable(): DateTime

DateTimeImmutable::createFromMutable(): DateTimeImmutable

In PHP 8.2, these method signatures have been changed the following:

DateTime::createFromImmutable(): static

DateTimeImmutable::createFromMutable(): static

 

This change makes more sense as it enhances the static insight options for classes that extend beyond DateTime as well as DateTimeImmutable. However, technically speaking, this is a break-in that could impact the custom implementations that are derived from one of the two classes.

 

Utf8_encode () and the utf8_decode () deprecations

In PHP 8.2 in PHP 8.2, using either the utf8_encode () or utf8_decode (), will cause these notices of deprecation:

Deprecated: Function utf8_encode() is deprecated

Deprecated: Function utf8_decode() is deprecated

The RFC claims that these functions are given a misleading name that can lead to confusion. They only change to ISO-8859-1 and UTF-8 as well as the name suggests a more broad usage. The RFC provides a more thorough explanation regarding the logic behind the RFC.

What is the alternative? The RFC suggests using mb_convert_encoding() instead.

 

Strtolower that is locale insensitive () and strtoupper ()

The strtolower () and strtoupper () are no longer localized. You can utilize strtolower mb_strtolower () if you’d like a locally-specific case converter.

 

Signature changes to various SPL methods

The methods for SPL types have been modified to make sure they are properly enforced. Signature type:

SplFileInfo::_bad_state_ex()

SplFileObject::getCsvControl()

SplFileObject::fflush()

SplFileObject::ftell()

SplFileObject::fgetc()

SplFileObject::fpassthru()

SplFileObject::hasChildren()

SplFileObject::getChildren()

 

New N modifier for PCRE

You are now able to utilize the N mod (NO_AUTO_CAPTURE) in Pcre* functions.

 

ODBC username and password

It is now possible to use the ODBC extension to escape users’ usernames and passwords in the scenario where both a connection string as well as username/password are provided, and the string needs to be added.

Similar to PDO_ODBC.

 

Deprecate ${} String Interpolation

PHP offers a variety of ways of embedding variables within strings. This RFC disapproves of two ways of doing this because they aren’t used frequently and frequently cause confusion.

“Hello ${world}”;

Deprecated: Using ${} in strings is deprecated

 

“Hello ${(world)}”;

Deprecated: Using ${} (variable variables) in strings is deprecated

To be precise: the two most well-known methods of interpolating strings still function:

“Hello {$world}”;

“Hello $world”;

 

Deprecate Supported Callables

Another change, though with a smaller consequence, is the partially supported callables are now being discarded too. Partially supported callables are callables that can be called using call_user_func($callable) but not by calling $callable() directly. The list of these types of callables is quite brief, in fact:

“self::method”

“parent::method”

“static::method”

[“self”, “method”]

[“parent”, “method”]

[“static”, “method”]

[“Foo”, “Bar::method”]

[new Foo, “Bar::method”]

The motivation behind this? It’s an important move in the right direction toward having the ability to use calls properties that can be typed.

 

Conclusion

Is PHP 8.2 released? Yes, with the PHP latest version there have been many new changes and PHP 8.2 new features added. You can either upgrade your current version or buy VPS server with PHP 8.2 already installed.

Leave a Reply

Your email address will not be published.