Placeholder canvas

PHP 8.2: What’s New In The New PHP Version

The latest version of PHP, PHP 8.2, introduces several enhancements, such as readonly classes, standalone types for null, false, and true, deprecated dynamic properties, and performance optimizations

PHP, a widely used server-side scripting language, continues to progress with each update. PHP 8.2 builds on the improvements introduced in PHP 8.0 and PHP 8.1, maintaining a renewed foundation.

In this blog post, we’ll explore key features of PHP 8.2, providing code samples for better understanding. Whether you’re an experienced PHP developer or a beginner, these changes aim to improve your coding experience, making applications more efficient and easier to maintain.

Let’s delve into the details of what’s new in PHP 8.2, covering new features, improvements, deprecations, and minor changes. 

Are you excited? We certainly are. Let’s get started!

What’s new in PHP 8.2?

PHP 8.2 introduces a range of advanced features, contributing to the ongoing evolution of the language. Upgrading to this latest version brings a multitude of benefits, enhancing your website in various aspects.

By adopting PHP 8.2, you not only unlock cutting-edge features but also improve your site’s security, ensure optimal syntax and execution, and maximize your online potential. Let’s explore some of the notable features that PHP 8.2 brings to the table:

  • Readonly Classes
  • Disjunctive Normal Form (DNF) Types
  • Standalone Types for null, false, and true

Readonly Classes

In PHP 8.2.0, a new feature called “readonly classes” is introduced. With this, you can designate a class as “readonly” by using the readonly modifier. When a class is marked as readonly, the readonly modifier is automatically applied to all declared properties within that class. 

Additionally, the creation of dynamic properties is restricted. Any attempt to add support for dynamic properties using the AllowDynamicProperties attribute will result in a compile-time error.

Here is an example of readonly classes:

  • Before PHP 8.2 (Enforcing Immutability with Getters):
class

User

{

    private

string

$name;

    public

function

__construct(string

$name) {

        $this->name = $name;

    }

    public

function

getName(): string

{

        return

$this->name;

    }

}

$user = new User("John");

// Attempt to change the name directly (would be allowed without the private property)

// $user->name = "Jane";  // Error: Property 'name' is private
  • After PHP 8.2 (Using Readonly Classes):
readonly class User {

    public readonly string $name;

    public function __construct(string $name) {

        $this->name = $name;

    }

}

$user = new User("John");

// Attempt to change the name directly (would cause a compile-time error)

// $user->name = "Jane";  // Error: Cannot modify readonly property 'name'

Disjunctive Normal Form (DNF) Types

Disjunctive Normal Form (DNF) serves as a standardized method for organizing boolean expressions involving a disjunction of conjunctions, essentially an OR of ANDs.

In PHP 8.2, the new DNF types feature applies DNF to type declarations, providing a standardized way to express combined Union and Intersection types that the parser can understand. Although simple, this feature is powerful when used appropriately.

Here’s an example using interface and class definitions:

interface A {}

interface B {}

interface C extends A {}

interface D {}

class W implements A {}

class X implements B {}

class Y implements A, B {}

class Z extends Y implements C {}

With DNF types, you can declare type constraints for properties, parameters, and return values like this:

// Accepts an object that either implements both interfaces A and B, or implements interface D

(A&B)|D

// Accepts an object that implements interface C, or a subclass of X that also implements interface D, or null

C|(X&D)|null

// Accepts an object that implements all three interfaces A, B, and D, or an integer, or null

(A&B&D)|int|null

Declaring properties as DNF forms will cause a parsing error if they are not. You may edit them as necessary:

Original: A&(B|D)

Rewritten: (A&B)|(A&D)

Original: A|(B&(D|W)|null)

Rewritten: A|(B&D)|(B&W)|null

It’s important to note that each segment of a DNF type must be unique. Declaring, for instance, (A&B)|(B&A) is incorrect because the two ORed segments make sense. 

Additionally, segments that are strict subsets of the other segment aren’t allowed, as the superset already includes all instances of the subset, making it redundant to use DNF.

Standalone Types for null, false, and true

PHP has traditionally included scalar types such as int, string, and bool. In PHP 8.0, union types were introduced, enabling values to belong to different types. However, false and null were only allowed as part of a union type and couldn’t be declared as standalone types, resulting in a fatal error if attempted.

For instance:

function spam(): null {}
function eggs(): false {}
The type Null cannot be used alone in... on line..., resulting in a fatal error.
The type False cannot be used alone in... on line..., resulting in a fatal error.

To address this limitation, PHP 8.2 now supports using false and null as standalone types. This enhancement makes PHP’s type system more expressive and comprehensive, allowing precise declaration of return types, parameter types, and property types.

Moreover, PHP 8.2 introduces the true type, completing the trio with false and null. The true type, like false, doesn’t allow coercion and is essentially a union type of PHP’s bool type.

However, attempting to declare all three types (true, false, and null) together in a union type will result in a compile-time fatal error to avoid redundancy.

Other Minor Improvements

PHP 8.2 introduces several new features and improvements:

  • /n Modifier for preg_ Functions:*

PHP 8.2 adds the /n (no capture) modifier to the preg_* function family. When used, this modifier ensures that any groups with meta-characters within parentheses won’t capture anything other than the named captured group. This simplifies complex regular expressions, allowing developers to choose and name specific captured groups.

  • Deprecation of ${} String Interpolation:

PHP 8.2 deprecates the use of ${} for string interpolation. Both direct use and the use of ${} for variable variables are deprecated. While this change may not significantly impact developers, it’s a move towards standardizing string interpolation methods.

Deprecated:

“Hello, ${world}!”;

“Hello, ${(world)}!”;

  • Random Extension Improvement:

PHP 8.2 addresses issues with the PHP random number generator. While PHP 7 introduced functions like random_int() and random_bytes(), PHP 8.2 takes it a step further by providing an extensible object-oriented interface for random number generation, improving upon the previous slow solution.

  • Additional RFCs:

PHP 8.2 includes several new functions and minor changes:

  • curl_upkeep function in Curl Extension: Introduces a new curl_upkeep function to the Curl extension, which calls the curl_easy_upkeep() function in libcurl.
  • New ini_parse_quantity function: PHP INI directives often use data sizes with multiplier suffixes (e.g., 25M for 25 Megabytes). The new ini_parse_quantity function parses these values and returns their data size in bytes.
  • New memory_reset_peak_usage function: This function resets the peak memory usage returned by memory_get_peak_usage(). It is useful when running the same action multiple times and needing to record each run’s peak memory utilization.

How to Update to PHP 8.2 on Nestify?

Updating to the latest PHP version on Nestify is easy; just follow the below steps:

  • Login to your Nestify account.
  • Select your sites.
  • Now go to Settings > PHP version, and select the latest version (Currently PHP 8.2).
Update to PHP 8.2

Congrats! You now have access to PHP’s most recent version, along with all of its features.

Final say

PHP 8.2 marks a significant step forward in the evolution of the language, offering a compelling range of new features and improvements. From enhanced type safety and performance boosts to security features and developer convenience additions, it empowers developers to create more robust, efficient, and secure applications. Whether you’re migrating existing projects or starting fresh, upgrading to PHP 8.2 unlocks a new level of potential and sets a solid foundation for future development.

FAQs on PHP 8.2

Q: When is the right time to switch to PHP 8.2?

PHP 8.2 comes with cool features, but before upgrading, check if your current libraries and tools work well with it. Look out for any big changes that might affect your code, and test everything thoroughly. It’s a good idea to set up a test area first before making changes to your live system.

Q: Will PHP 8.2 cause problems with my existing code?

Yes, there are a few changes that might need adjustments in your code. For example, dynamic properties are deprecated, DateTime functions have new return types, and how arrays merge has changed. Take a careful look at the migration guide and update your code accordingly.

Q: Can I use PHP 8.2 with my old code?

PHP 8.2 aims to work with your existing code, but you might need to make some small changes, as we mentioned earlier. It’s always smart to thoroughly test your application before upgrading to make sure everything runs smoothly.

Q: Where can I get more information about PHP 8.2?

To learn more about PHP 8.2, visit the official PHP website. They have detailed documentation and migration guides at PHP: Documentation. You can also find helpful resources like blog posts, tutorials, and community forums that offer additional insights and learning opportunities.

Want faster WordPress?

WordPress Speed Optimization

Try our AWS powered WordPress hosting for free and see the difference for yourself.

No Credit Card Required.

Whitelabel Web Hosting Portal Demo

Launching WordPress on AWS takes just one minute with Nestify.

Launching WooCommerce on AWS takes just one minute with Nestify.